(() => {
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b2) => (typeof require !== "undefined" ? require : a)[b2]
}) : x)(function(x) {
if (typeof require !== "undefined")
return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
// src/shared/enums.mjs
var CloseCode = {
gameNotFound: 0,
gameFull: 0,
badName: 0,
mainMenu: 0,
gameIdleExceeded: 0,
corruptedLoginData0: 0,
corruptedLoginData1: 0,
corruptedLoginData2: 0,
corruptedLoginData3: 0,
corruptedLoginData4: 0,
corruptedLoginData5: 0,
gameMaxPlayersExceeded: 0,
gameDestroyUser: 0,
joinGameOutOfOrder: 0,
gameShuttingDown: 0,
readyBeforeReady: 0,
booted: 0,
gameErrorOnUserSocket: 0,
uuidNotFound: 0,
sessionNotFound: 0,
clusterFullCpu: 0,
clusterFullMem: 0,
noClustersAvailable: 0,
locked: 0
};
var i = 4e3;
Object.keys(CloseCode).forEach((k) => {
CloseCode[k] = i++;
});
var CommCode = {
createPrivateGame: 0,
switchTeam: 0,
changeCharacter: 0,
pause: 0,
announcement: 0,
updateBalance: 0,
reload: 0,
refreshGameState: 0,
switchTeamFail: 0,
expireUpgrade: 0,
bootPlayer: 0,
banPlayer: 0,
loginRequired: 0,
gameLocked: 0,
reportPlayer: 0,
banned: 0,
metaGameState: 0,
syncMe: 0,
explode: 0,
keepAlive: 0,
musicInfo: 0,
hitMeHardBoiled: 0,
beginShellStreak: 0,
endShellStreak: 0,
startReload: 0,
fire: 0,
melee: 0,
throwGrenade: 0,
info: 0,
eventModifier: 0,
playerInfo: 0,
gameOptions: 0,
gameAction: 0,
requestGameOptions: 0,
gameJoined: 0,
socketReady: 0,
addPlayer: 0,
removePlayer: 0,
chat: 0,
syncThem: 0,
syncAmmo: 0,
die: 0,
hitThem: 0,
hitMe: 0,
collectItem: 0,
spawnItem: 0,
respawn: 0,
respawnDenied: 0,
swapWeapon: 0,
joinGame: 0,
observeGame: 0,
ping: 0,
pong: 0,
clientReady: 0,
requestRespawn: 0,
joinPublicGame: 0,
joinPrivateGame: 0
};
var i = 0;
Object.keys(CommCode).forEach((k) => {
CommCode[k] = i++;
});
var Team = {
blue: 1,
red: 2
};
var GameType = {
ffa: 0,
teams: 1,
ctf: 2,
king: 3
};
var GameTypes = [
{ shortName: "FFA", longName: "Free For All", value: 0 },
{ shortName: "Teams", longName: "Teams", value: 1 },
{ shortName: "Spatula", longName: "Captula the Spatula", value: 2 },
{ shortName: "King", longName: "King of the Coop", value: 3 }
];
var DmgType = [
{ name: "Eggk47" },
{ name: "Scrambler" },
{ name: "FreeRanger" },
{ name: "Cluck9mm" },
{ name: "Rpegg" },
{ name: "Whipper" },
{ name: "Crackshot" },
{ name: "TriHard" },
{ name: "Grenade" },
{ name: "Melee" },
{ name: "Fall" }
];
var SyncRate = 10;
var FramesBetweenSyncs = Math.ceil(30 / SyncRate);
var Reward = {
perKill: 10,
video: 100,
perKillModTwo: 20,
discord: "rew_1200",
tiktok: "rew_1208",
Instagram: "rew_1219",
Steam: "rew_1223",
Facebook: "rew_1227",
Twitter: "rew_1234",
Twitch: "rew_twitch_social"
};
var FeedbackType = {
comment: 0,
// For the heaping of praise upon us, probably. Definitely. Yeah.
feature: 1,
// Feature requests
bug: 2,
// Well, you know... bugs.
purchase: 3,
// Issues with item and golden egg purchases
account: 4,
// Account and privacy issues
abuse: 5,
// For people to bitch about other people "hacking"
other: 6,
// Who knows... Probably porn.
deleteAccount: 7
// for account delete requests
};
var ShellStreak = {
HardBoiled: 1,
EggBreaker: 2
};
var CHICKWINNER = {
dailyLimit: 3,
cooldown: 240,
dailyCooldown: 86400
};
var Slot = {
Primary: 0,
Secondary: 1
};
var ItemType2 = {
Hat: 1,
Stamp: 2,
Primary: 3,
Secondary: 4,
Grenade: 6,
Melee: 7
};
var CharClass = {
Soldier: 0,
Scrambler: 1,
Ranger: 2,
Eggsploder: 3,
Whipper: 4,
Crackshot: 5,
TriHard: 6
};
CharClass.length = Object.keys(CharClass).length;
var StatsArr = [
"kills",
"deaths",
"streak",
"killsCluck9mm",
"killsGrenade",
"killsRpegg",
"killsEggk47",
"killsScrambler",
"killsFreeRanger",
"killsWhipper",
"killsCrackshot",
"killsTriHard",
"killsMelee",
"killsPrivate",
"killsPublic",
"killsKing",
"killsSpatula",
"killsTeams",
"killsFFA",
"deathsCluck9mm",
"deathsGrenade",
"deathsRpegg",
"deathsEggk47",
"deathsScrambler",
"deathsFreeRanger",
"deathsWhipper",
"deathsCrackshot",
"deathsTriHard",
"deathsMelee",
"deathsPrivate",
"deathsPublic",
"deathsKing",
"deathsSpatula",
"deathsTeams",
"deathsFFA",
"kotcCaptured",
"kotcWins"
];
// src/version.mjs
var versionNumber = "0.47.4";
// src/shared/pool.mjs
var Pool = class {
constructor(constructorFn, size) {
this.size = 0;
this.originalSize = size;
this.constructorFn = constructorFn;
this.objects = [];
this.idx = 0;
this.numActive = 0;
this.expand(size);
}
expand(num) {
for (var i2 = 0; i2 < num; i2++) {
var obj = this.constructorFn();
obj.id = i2 + this.size;
obj.active = false;
this.objects.push(obj);
}
this.size += num;
}
retrieve(id) {
if (id != void 0) {
while (id >= this.size) {
this.expand(this.originalSize);
}
this.numActive++;
this.objects[id].active = true;
return this.objects[id];
}
var i2 = this.idx;
do {
i2 = (i2 + 1) % this.size;
var obj = this.objects[i2];
if (!obj.active) {
this.idx = i2;
this.numActive++;
obj.active = true;
return obj;
}
} while (i2 != this.idx);
this.expand(this.originalSize);
console.log("Expanding pool for: " + this.objects[0].constructor.name + " to: " + this.size);
return this.retrieve();
}
recycle(obj) {
obj.active = false;
this.numActive--;
}
forEachActive(fn) {
for (var i2 = 0; i2 < this.size; i2++) {
var obj = this.objects[i2];
if (obj.active === true) {
fn(obj, i2);
}
}
}
};
// src/client/clientComm.mjs
var OutBuffer = class {
constructor(size) {
this.idx = 0;
this.arrayBuffer = new ArrayBuffer(size);
this.buffer = new Uint8Array(this.arrayBuffer, 0, size);
}
send(ws2) {
var b2 = new Uint8Array(this.arrayBuffer, 0, this.idx);
ws2.send(b2);
CommOut.bufferPool.recycle(this);
}
packInt8(val) {
this.buffer[this.idx] = val & 255;
this.idx++;
}
packInt16(val) {
this.buffer[this.idx] = val & 255;
this.buffer[this.idx + 1] = val >> 8 & 255;
this.idx += 2;
}
packInt24(val) {
this.buffer[this.idx] = val & 255;
this.buffer[this.idx + 1] = val >> 8 & 255;
this.buffer[this.idx + 2] = val >> 16 & 255;
this.idx += 3;
}
packInt32(val) {
this.buffer[this.idx] = val & 255;
this.buffer[this.idx + 1] = val >> 8 & 255;
this.buffer[this.idx + 2] = val >> 16 & 255;
this.buffer[this.idx + 3] = val >> 24 & 255;
this.idx += 4;
}
packRadU(val) {
this.packInt24(val * 2097152);
}
packRad(val) {
this.packInt16((val + Math.PI) * 8192);
}
packFloat(val) {
this.packInt16(val * 256);
}
packDouble(val) {
this.packInt32(val * 1048576);
}
packString(str) {
if (typeof str !== "string")
str = "";
this.packInt8(str.length);
for (var i2 = 0; i2 < str.length; i2++) {
this.packInt16(str.charCodeAt(i2));
}
}
packLongString(str) {
if (typeof str !== "string")
str = "";
this.packInt16(str.length);
for (var i2 = 0; i2 < str.length; i2++) {
this.packInt16(str.charCodeAt(i2));
}
}
};
var CommOut = class {
static buffer = null;
static bufferPool = new Pool(() => {
return new OutBuffer(16384);
}, 2);
static getBuffer() {
var b2 = this.bufferPool.retrieve();
b2.idx = 0;
return b2;
}
};
var CommIn = class {
static buffer;
static idx;
static init(buf) {
this.buffer = new Uint8Array(buf);
this.idx = 0;
}
static isMoreDataAvailable() {
return Math.max(0, this.buffer.length - this.idx);
}
static peekInt8U() {
return this.buffer[this.idx];
}
static unPackInt8U() {
var i2 = this.idx;
this.idx++;
return this.buffer[i2];
}
static unPackInt8() {
var v = this.unPackInt8U();
return (v + 128) % 256 - 128;
}
static unPackInt16U() {
var i2 = this.idx;
this.idx += 2;
return this.buffer[i2] + this.buffer[i2 + 1] * 256;
}
static unPackInt24U() {
var i2 = this.idx;
this.idx += 3;
return this.buffer[i2] + this.buffer[i2 + 1] * 256 + this.buffer[i2 + 2] * 65536;
}
static unPackInt32U() {
var i2 = this.idx;
this.idx += 4;
return this.buffer[i2] + this.buffer[i2 + 1] * 256 + this.buffer[i2 + 2] * 65536 + this.buffer[i2 + 3] * 16777216;
}
static unPackInt16() {
var v = this.unPackInt16U();
return (v + 32768) % 65536 - 32768;
}
static unPackInt32() {
var v = this.unPackInt32U();
return (v + 2147483648) % 4294967296 - 2147483648;
}
// Unsigned radians (0 to 6.2831)
static unPackRadU() {
return this.unPackInt24U() / 2097152;
}
// Signed radians (-3.1416 to 3.1416)
static unPackRad() {
var v = this.unPackInt16U() / 8192;
return v - Math.PI;
}
// Float value packing (-327.68 to 327.67)
static unPackFloat() {
return this.unPackInt16() / 256;
}
static unPackDouble() {
return this.unPackInt32() / 1048576;
}
static unPackString(maxLen) {
maxLen = maxLen || 255;
var len = Math.min(this.unPackInt8U(), maxLen);
return this.unPackStringHelper(len);
}
static unPackLongString(maxLen) {
maxLen = maxLen || 16383;
var len = Math.min(this.unPackInt16U(), maxLen);
return this.unPackStringHelper(len);
}
static unPackStringHelper(len) {
let remainder = this.isMoreDataAvailable();
if (remainder < len)
return 0;
var str = new String();
for (var i2 = 0; i2 < len; i2++) {
var c = this.unPackInt16U();
if (c > 0)
str += String.fromCodePoint(c);
}
return str;
}
};
// src/client/bawk.mjs
var BAWK2 = class _BAWK {
static init() {
console.log("BAWK! initializing...");
var ctx = new AudioContext();
this.audioCtx = ctx;
this.children = [];
this.sounds = {};
this.position = { x: 0, y: 0, z: 0 };
this.orientation = { x: 0, y: 0, z: -1 };
this.detectFormats();
this.gainNode = ctx.createGain();
this.compNode = ctx.createDynamicsCompressor();
this.compNode.connect(this.gainNode);
this.gainNode.connect(ctx.destination);
this.inputNode = this.compNode;
if (this.volume != void 0)
this.gainNode.gain.value = this.volume;
}
static dispose() {
this.audioCtx.close();
}
static setFormats(formats) {
this.formats = formats;
}
static detectFormats() {
var formats = _BAWK.formats || {
// Organize these from most to least desirable
"webm": "audio/webm",
"ogg": "audio/ogg",
"mp3": "audio/mpeg"
};
if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
delete formats["webm"];
}
var el = document.createElement("audio");
var keys = Object.keys(formats);
for (var k of keys) {
var canPlay = el.canPlayType(formats[k]);
console.log("BAWK! testing " + k, canPlay);
if (canPlay) {
_BAWK.format = k;
console.log("BAWK! selected " + k);
break;
}
}
;
}
static suspend() {
if (_BAWK.audioCtx)
_BAWK.audioCtx.suspend();
}
static resume() {
if (_BAWK.audioCtx)
_BAWK.audioCtx.resume();
}
// Loads an audio file or audio sprite, depending on the extension
// *.json is assumed to be an audio sprite
static async load(url, keyname) {
if (!_BAWK.audioCtx)
_BAWK.init();
var filename = url.match(/[^/\\&\?]+\..{1,4}(?=([\?\#&].*$|$))/)[0];
var ext = filename.match(/[^\.]*$/).join("");
var name = filename.replace("." + ext, "");
if (ext == "json") {
await _BAWK.loadSprite(url);
} else {
await _BAWK.loadSound(url, keyname || name);
}
}
// Loads a single audio file.
static async loadSound(url, name) {
url = url.replace("*", _BAWK.format);
var buffer = await _BAWK.getAudioBuffer(url);
if (!buffer)
return;
if (_BAWK.sounds[name]) {
console.warn('BAWK! duplicate sound name, "' + name + '" will be over-written');
}
_BAWK.sounds[name] = {
buffer
};
}
// Loads an audiosprite (https://www.npmjs.com/package/audiosprite)
static async loadSprite(url) {
var response = await fetch(url);
var json = await response.json();
var buffer = await _BAWK.loadSpriteBuffer(url, json);
Object.keys(json.spritemap).forEach((k) => {
var s = json.spritemap[k];
_BAWK.sounds[k] = {
buffer,
start: s.start,
end: s.end
};
});
}
static async loadSpriteBuffer(url, data2) {
for (var fileName of data2.resources) {
if (fileName.endsWith(_BAWK.format)) {
break;
}
}
var filePath = url.match(/.+\//) + fileName;
console.log("BAWK! loading " + filePath);
return await _BAWK.getAudioBuffer(filePath + "?" + versionNumber);
}
static async getAudioBuffer(path) {
var response = await _BAWK.request(path);
var audioBuffer = await new Promise((success, fail) => {
_BAWK.audioCtx.decodeAudioData(response, success, fail);
});
return audioBuffer;
}
static request(path) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("GET", path, true);
xhr.responseType = "arraybuffer";
let id = Loader.addTask();
xhr.onprogress = (event) => {
id = Loader.progress(id, event.loaded, event.total);
};
xhr.onload = () => {
if (xhr.status != 200) {
console.log("ERROR");
reject();
} else {
resolve(xhr.response);
}
Loader.finish(id);
};
xhr.send();
});
}
static setVolume(vol) {
_BAWK.volume = vol;
if (_BAWK.gainNode)
_BAWK.gainNode.gain.value = vol;
}
static getVolume() {
return _BAWK.volume;
}
static play(name, node, alt) {
var ctx = _BAWK.audioCtx;
node = node || _BAWK.inputNode;
if (ctx.state === "suspended") {
_BAWK.resume();
}
var sound = _BAWK.sounds[name];
if (!sound) {
let altMsg;
if (alt) {
altMsg = ` or ${alt}`;
sound = _BAWK.sounds[alt];
}
if (!sound) {
console.error(`BAWK! ${name} ${altMsg} not found. Did you wait for it to load?`);
return false;
}
}
if (sound.end) {
var offset = sound.start;
var duration = sound.end - offset;
}
var source = ctx.createBufferSource();
source.buffer = sound.buffer;
source.connect(node);
if (duration) {
source.start(0, offset, duration);
} else {
source.start();
}
return source;
}
// As a shortcut, we'll use references to objects that have
// x, y, and z properties, such as Vector3 in BabylonJS and three.js
static attach(position, orientation) {
_BAWK.position = position;
_BAWK.orientation = orientation;
}
static detach() {
_BAWK.position = { x: _BAWK.position.x, y: _BAWK.position.y, z: _BAWK.position.z };
_BAWK.orientation = { x: _BAWK.orientation.x, y: _BAWK.orientation.y, z: _BAWK.orientation.z };
}
static setPosition(vector) {
var listener = _BAWK.audioCtx.listener;
if (listener.positionX) {
listener.positionX.value = vector.x;
listener.positionY.value = vector.y;
listener.positionZ.value = vector.z;
} else {
listener.setPosition(vector.x, vector.y, vector.z);
}
}
static setOrientation(vector) {
var listener = _BAWK.audioCtx.listener;
if (listener.forwardX) {
listener.forwardX.value = vector.x;
listener.forwardY.value = vector.y;
listener.forwardZ.value = vector.z;
} else {
listener.setOrientation(vector.x, vector.y, vector.z, 0, 1, 0);
}
}
static addChild(child) {
_BAWK.children.push(child);
}
static removeChild(child) {
_BAWK.children.splice(_BAWK.children.indexOf(child), 1);
}
static update() {
if (_BAWK.position)
_BAWK.setPosition(_BAWK.position);
if (_BAWK.orientation)
_BAWK.setOrientation(_BAWK.orientation);
for (var c of _BAWK.children)
c.update();
}
};
var PositionalAudio = class _PositionalAudio {
constructor(opts, pannerOpts) {
BAWK2.addChild(this);
opts = opts || {};
this.numChannels = opts.numChannels || 16;
this.numPlaying = 0;
this.channels = [];
this.nextChannelIdx = 0;
this.gainNode = BAWK2.audioCtx.createGain();
this.gainNode.connect(BAWK2.inputNode);
for (var i2 = 0; i2 < this.numChannels; i2++) {
var node = BAWK2.audioCtx.createPanner(pannerOpts);
node.connect(this.gainNode);
this.channels.push({
parent: this,
source: null,
position: { x: 0, y: 0, z: 0 },
follow: false,
node
});
}
}
dispose() {
this.gainNode.disconnect();
BAWK2.removeChild(this);
}
setVolume(vol) {
this.gainNode.gain.value = vol;
}
getVolume() {
return this.gainNode.gain.value;
}
play(name, pos, follow) {
if (!BAWK2.sounds[name]) {
console.error("BAWK! " + name + " not found. Did you wait for it to load?");
return;
}
var c = this.findFreeChannel(pos);
if (c.source) {
c.source.stop();
}
var node = c.node;
c.position = pos;
c.follow = follow;
_PositionalAudio.setNodePosition(node, pos);
c.source = BAWK2.play(name, node);
c.source.channel = c;
c.source.onended = _PositionalAudio.onEnded;
this.numPlaying++;
}
update() {
for (var c of this.channels) {
if (c.source && c.follow) {
_PositionalAudio.setNodePosition(c.node, c.position);
}
}
}
static setNodePosition(node, pos) {
var y = BAWK2.position.y + (pos.y - BAWK2.position.y) * 4;
if (node.positionX) {
node.positionX.value = pos.x;
node.positionY.value = y;
node.positionZ.value = pos.z;
} else {
node.setPosition(pos.x, y, pos.z);
}
}
// Do our best to find a channel with no sound currently playing
// Failing that, hijack the one that is farthest from the listener
findFreeChannel(pos) {
var channels = this.channels;
var numChannels = this.numChannels;
var listener = BAWK2.position;
if (this.numPlaying < numChannels) {
for (var c of channels) {
if (!c.source)
return c;
}
}
var farthestDist = -1;
var farthestChannel;
for (var c of channels) {
var dist = Math.pow(pos.x - listener.x, 2) + Math.pow(pos.y - listener.y, 2) + Math.pow(pos.z - listener.z, 2);
if (dist > farthestDist) {
farthestDist = dist;
farthestChannel = c;
}
}
return farthestChannel;
}
static onEnded(e2) {
e2.target.channel.parent.numPlaying--;
e2.target.channel.source = null;
e2.target.channel = null;
}
};
window.BAWK = BAWK2;
// src/client/closure/globals.mjs
var G = {
productBlockAds: false,
vipSubEnded: false
};
// src/client/stats.mjs
var StatsObj = class {
constructor() {
this.statStateTemp = {
total: 0,
mode: {
public: 0,
private: 0
},
dmgType: {
pistol: 0,
grenade: 0,
rpegg: 0,
eggk: 0,
scrambler: 0,
ranger: 0,
whipper: 0,
crackshot: 0,
trihard: 0,
melee: 0,
fall: 0
},
gameType: {
kotc: 0,
spatula: 0,
team: 0,
ffa: 0
},
kdr: {
private: 0,
public: 0,
ffa: 0,
teams: 0,
kotc: 0,
spatula: 0
}
};
this.kills = Object.create(this.statStateTemp);
this.deaths = Object.create(this.statStateTemp);
this.gameType = {
kotc: {
captured: 0,
wins: 0
}
};
this.streak = 0;
this.dateReset = null;
}
get() {
return {
kills: this.kills,
deaths: this.deaths,
gameType: this.gameType,
streak: this.streak,
dateReset: this.dateReset
};
}
set(val) {
if (!val || val.error !== void 0) {
return vueApp.showGenericPopup("uh_oh", "auth_stat_error_msg", "ok");
}
if (val.kills !== void 0) {
this.kills = this.updateStats(val.kills, "kills");
}
if (val.deaths !== void 0) {
this.deaths = this.updateStats(val.deaths, "deaths");
}
if (val.gameType !== void 0) {
this.gameType = {
kotc: {
captured: val.gameType.kotc.captured !== void 0 ? val.gameType.kotc.captured : this.gameType.kotc.captured,
wins: val.gameType.kotc.wins !== void 0 ? val.gameType.kotc.wins : this.gameType.kotc.wins
}
};
}
if (val.streak) {
this.streak = val.streak !== void 0 ? val.streak : this.streak;
}
}
updateStats(val, type) {
return {
total: val.total !== void 0 ? val.total : this[type].deaths,
mode: {
public: val.mode.public !== void 0 ? val.mode.public : this[type].mode.public,
private: val.mode.private !== void 0 ? val.mode.private : this[type].mode.private
},
dmgType: {
pistol: val.dmgType.pistol !== void 0 ? val.dmgType.pistol : this[type].dmgType.pistol,
grenade: val.dmgType.grenade !== void 0 ? val.dmgType.grenade : this[type].dmgType.grenade,
rpegg: val.dmgType.rpegg !== void 0 ? val.dmgType.rpegg : this[type].dmgType.rpegg,
eggk: val.dmgType.eggk !== void 0 ? val.dmgType.eggk : this[type].dmgType.eggk,
scrambler: val.dmgType.scrambler !== void 0 ? val.dmgType.scrambler : this[type].dmgType.scrambler,
ranger: val.dmgType.ranger !== void 0 ? val.dmgType.ranger : this[type].dmgType.ranger,
whipper: val.dmgType.whipper !== void 0 ? val.dmgType.whipper : this[type].dmgType.whipper,
crackshot: val.dmgType.crackshot !== void 0 ? val.dmgType.crackshot : this[type].dmgType.crackshot,
trihard: val.dmgType.trihard !== void 0 ? val.dmgType.trihard : this[type].dmgType.trihard,
melee: val.dmgType.melee !== void 0 ? val.dmgType.melee : this[type].dmgType.melee,
fall: val.dmgType.fall !== void 0 ? val.dmgType.fall : this[type].dmgType.fall
},
gameType: {
kotc: val.gameType.kotc !== void 0 ? val.gameType.kotc : this[type].gameType.kotc,
spatula: val.gameType.spatula !== void 0 ? val.gameType.spatula : this[type].gameType.spatula,
team: val.gameType.team !== void 0 ? val.gameType.team : this[type].gameType.team,
ffa: val.gameType.ffa !== void 0 ? val.gameType.ffa : this[type].gameType.ffa
}
};
}
};
// src/client/sessionWorker.mjs
var sessionRenewalWorkerCode = `
var sessionId;
var servicesServer;
var timeout;
onmessage = function (e) {
servicesServer = e.data.servicesServer;
sessionId = e.data.sessionId;
console.log(getTime(), 'Session: worker received session ID:', sessionId);
clearTimeout(timeout);
if (sessionId !== null) {
timeout = setTimeout(() => renewSession(), 600000);
}
}
function getTime () {
let d = new Date();
return d.toTimeString();
}
function renewSession () {
callRenew(res => {
console.log(getTime(), 'Session: renew result:', res.data);
if (res.data === 'renewed') {
console.log(getTime(), 'Session: session renewed');
timeout = setTimeout(() => renewSession(), 600000);
}
else {
console.log(getTime(), 'Session: session expired');
postMessage('expired');
}
},
() => {
console.log(getTime(), 'Session: failed to renew - Trying again in 30 seconds');
timeout = setTimeout(() => renewSession(), 30000);
}
);
}
function callRenew (successCallback, errorCallback) {
console.log(getTime(), 'Session: callRenew');
try {
var servicesWs = new WebSocket(servicesServer);
} catch (e) {
errorCallback();
}
servicesWs.onopen = function (e) {
servicesWs.send(JSON.stringify({
cmd: 'renewSession',
sessionId: sessionId
}));
};
servicesWs.onmessage = function (e) {
var response = null;
try {
response = JSON.parse(e.data);
successCallback(response);
} catch (e) {
errorCallback();
}
servicesWs.close();
};
servicesWs.onerror = function (e) {
errorCallback();
};
}
`;
var blob = new Blob([sessionRenewalWorkerCode]);
var blobURL = window.URL.createObjectURL(blob);
var sessionRenewalWorker = new Worker(blobURL);
sessionRenewalWorker.onmessage = (e2) => {
if (e2.data === "expired") {
vueApp.showGenericPopup("session_expired", "session_expired_msg", "ok");
}
};
// src/client/playerAccount.mjs
var PlayerAccount = class {
constructor() {
this.pickedWeapons = [];
for (var cIdx = 0; cIdx < CharClass.length; cIdx++) {
var defaultPicks = [
G.catalog.forClass[cIdx].primaryWeapons[0],
G.catalog.forClass[cIdx].secondaryWeapons[0]
];
this.pickedWeapons.push(defaultPicks);
}
;
this.firebaseId = null;
this.session = null;
this.maskedEmail = null;
this.classIdx = 0;
this.inventory = [];
this.hatItem = null;
this.stampItem = null;
this.grenadeItem = G.catalog.grenades[0];
this.meleeItem = G.catalog.melee[0];
this.colorIdx = 0;
this.kills = 0;
this.deaths = 0;
this.streak = 0;
this.currentBalance = 0;
this.upgradeProductId = null;
this.killMultiplier = 1;
this.hideAds = false;
this.maybeSchoolEmail = false;
this.upgradeExpiryDate = null;
this.upgradeIsExpired = null;
this.upgradeName = "";
this.isSubscriber = false;
this.twitchLinked = false;
this.twitchName = "";
this.contentCreator = false;
this.dateCreated = null;
this.accountAge = null;
this.statsCurrent = new StatsObj();
this.statsLifetime = new StatsObj();
this.eggsSpent = 0;
this.eggsSpentMonthly = 0;
this.eggsEarnedBalance = 0;
this._firebaseId;
Object.defineProperty(this, "firebaseId", {
get: function() {
return this._firebaseId;
},
set: function(newVal) {
this._firebaseId = newVal;
vueApp.firebaseId = this._firebaseId;
}
});
this._id;
Object.defineProperty(this, "id", {
get: function() {
return this._id;
},
set: function(newVal) {
this._id = newVal;
vueApp.id = this._id;
}
});
this._isAnonymous;
Object.defineProperty(this, "isAnonymous", {
get: function() {
return this._isAnonymous;
},
set: function(newVal) {
this._isAnonymous = newVal;
vueApp.isAnonymous = this._isAnonymous;
vueApp.googleAnalytics.isUser = this._isAnonymous ? "Unclaimed" : "Claimed";
ga("set", "dimension1", vueData.googleAnalytics.isUser);
}
});
this._currentBalance;
Object.defineProperty(this, "currentBalance", {
get: function() {
return this._currentBalance;
},
set: function(newBalance) {
this._currentBalance = newBalance;
vueApp.eggs = this._currentBalance;
}
});
this._kills;
Object.defineProperty(this, "kills", {
get: function() {
return this._kills;
},
set: function(newKills) {
this._kills = newKills;
vueApp.kills = this._kills;
}
});
this._deaths;
Object.defineProperty(this, "deaths", {
get: function() {
return this._deaths;
},
set: function(newDeaths) {
this._deaths = newDeaths;
vueApp.deaths = this._deaths;
}
});
this._kdr;
Object.defineProperty(this, "kdr", {
get: function() {
return this._kdr;
},
set: function(newKdr) {
this._kdr = newKdr;
vueApp.kdr = this._kdr;
}
});
this._kdrLifetime;
Object.defineProperty(this, "kdrLifetime", {
get: function() {
return this._kdrLifetime;
},
set: function(val) {
this._kdrLifetime = val;
vueApp.kdrLifetime = this._kdrLifetime;
}
});
this._streak;
Object.defineProperty(this, "streak", {
get: function() {
return this._streak;
},
set: function(newStreak) {
this._streak = newStreak;
vueApp.streak = this._streak;
}
});
this._statsCurrent = new StatsObj();
Object.defineProperty(this, "statsCurrent", {
get: function() {
return this._statsCurrent;
},
set: function(val) {
this._statsCurrent.set(val);
this.kills = this._statsCurrent.kills.total;
this.deaths = this._statsCurrent.deaths.total;
this.streak = this._statsCurrent.streak;
this.kdr = Math.floor(this._statsCurrent.kills.total / Math.max(this._statsCurrent.deaths.total, 1) * 100) / 100;
vueApp.statsCurrent = this._statsCurrent;
}
});
this._statsLifetime = new StatsObj();
Object.defineProperty(this, "statsLifetime", {
get: function() {
return this._statsLifetime;
},
set: function(val) {
this._statsLifetime.set(val);
this.kdrLifetime = Math.floor(this._statsLifetime.kills.total / Math.max(this._statsLifetime.deaths.total, 1) * 100) / 100;
vueApp.statsLifetime = this._statsLifetime;
}
});
this._eggsSpent;
Object.defineProperty(this, "eggsSpent", {
get: function() {
return this._eggsSpent;
},
set: function(eggs) {
this._eggsSpent = eggs === null ? 0 : eggs;
vueApp.eggsSpent = this._eggsSpent;
}
});
this._eggsSpentMonthly;
Object.defineProperty(this, "eggsSpentMonthly", {
get: function() {
return this._eggsSpentMonthly;
},
set: function(newName) {
this._eggsSpentMonthly = newName;
vueApp.eggsSpentMonthly = this._eggsSpentMonthly;
}
});
this._eggsEarnedBalance;
Object.defineProperty(this, "eggsEarnedBalance", {
get: function() {
return this._eggsEarnedBalance;
},
set: function(eggs) {
if (eggs === void 0) {
return;
}
this._eggsEarnedBalance = eggs === null ? 0 : eggs;
vueApp.eggsEarnedBalance = this._eggsEarnedBalance;
}
});
this._playerName;
Object.defineProperty(this, "playerName", {
get: function() {
return this._playerName;
},
set: function(newName) {
this._playerName = newName;
vueApp.playerName = this._playerName;
}
});
this._maskedEmail;
Object.defineProperty(this, "maskedEmail", {
get: function() {
return this._maskedEmail;
},
set: function(newValue) {
this._maskedEmail = newValue;
vueApp.maskedEmail = this._maskedEmail;
}
});
this._isEmailVerified;
Object.defineProperty(this, "isEmailVerified", {
get: function() {
return this._isEmailVerified;
},
set: function(newValue) {
this._isEmailVerified = newValue;
vueApp.isEmailVerified = this._isEmailVerified;
}
});
this._isSubscriber;
Object.defineProperty(this, "isSubscriber", {
get: function() {
return this._isSubscriber;
},
set: function(newValue) {
this._isSubscriber = newValue;
vueApp.isSubscriber = newValue;
}
});
this._upgradeName;
Object.defineProperty(this, "upgradeName", {
get: function() {
return this._upgradeName;
},
set: function(newValue) {
this._upgradeName = newValue;
vueApp.upgradeName = newValue;
}
});
this._hideAds;
Object.defineProperty(this, "hideAds", {
get: function() {
return this._hideAds;
},
set: function(val) {
vueApp.hideAds = val ? true : false;
}
});
this._twitchLinked;
Object.defineProperty(this, "twitchLinked", {
get() {
return this._twitchLinked;
},
set(val) {
this._twitchLinked = val;
vueApp.twitchLinked = val;
}
});
this._twitchName;
Object.defineProperty(this, "twitchName", {
get() {
return this._twitchName;
},
set(val) {
this._twitchName = val;
vueApp.twitchName = val;
}
});
this.isItemOwned;
Object.defineProperty(this, "isItemOwned", {
value: function(val) {
if (!val)
return false;
for (var i2 = 0; i2 < this.inventory.length; i2++) {
if (this.inventory[i2] && this.inventory[i2].id === val.id) {
return true;
}
}
return false;
}
});
this._contentCreator;
Object.defineProperty(this, "contentCreator", {
get() {
return this._contentCreator;
},
set(val) {
if (val) {
this._contentCreator = true;
vueApp.contentCreator = this._contentCreator;
}
}
});
this._dateCreated;
Object.defineProperty(this, "dateCreated", {
get() {
return this._dateCreated;
},
set(val) {
if (val) {
const date = new Date(val).toLocaleDateString();
this._dateCreated = date;
vueApp.accountCreated = date;
} else {
vueApp.accountCreated = null;
}
}
});
}
loggedOut() {
this.firebaseId = null;
this.id = null;
this.session = null;
this.sessionId = null;
this.kills = 0;
this.deaths = 0;
this.streak = 0;
this.currentBalance = 0;
this.classIdx = 0;
this.inventory = [];
this.pickedWeapons = [];
this.stampItem = null;
this.grenadeItem = G.catalog.findItemById(16e3);
this.meleeItem = G.catalog.findItemById(15e3);
this.hatItem = null;
this.colorIdx = 0;
this.killMultiplier = 1;
this.hideAds = false;
this.maybeSchoolEmail = false;
this.isAnonymous = true;
this.upgradeIsExpired = null;
this.upgradeExpiryDate = null;
this.upgradeName = "";
this.isSubscriber = false;
this.twitchLinked = false;
this.twitchName = "";
this.contentCreator = false;
this.dateCreated = null;
this.eggsSpent = 0;
this.eggsSpentMonthly = 0;
this.eggsEarnedBalance = 0;
this.statsCurrent = new StatsObj();
this.statsLifetime = new StatsObj();
for (var cIdx = 0; cIdx < CharClass.length; cIdx++) {
var defaultPicks = [
G.catalog.forClass[cIdx].primaryWeapons[0],
G.catalog.forClass[cIdx].secondaryWeapons[0]
];
this.pickedWeapons.push(defaultPicks);
}
sessionRenewalWorker.postMessage({
sessionId: null
});
G.adminRoles = 0;
}
loggingOut() {
this.loggedOut();
this.applyLoadoutObject();
this.getPrimaryWeapon();
this.getSecondaryWeapon();
this.setClass(this.classIdx);
vueApp.signOut();
}
setClass(classIdx) {
if (classIdx >= G.classes.length)
classIdx = 0;
this.classIdx = classIdx;
vueApp.classIdx = this.classIdx;
}
pickWeapon(slot, weaponItem) {
if (weaponItem.item_type_id === ItemType.Primary) {
this.setClass(weaponItem.exclusive_for_class);
}
var foundInList = G.catalog.findItemInListById(weaponItem, G.catalog.forClass[this.classIdx].forWeaponSlot[slot]);
if (foundInList === false) {
weaponItem = G.catalog.forClass[this.classIdx].forWeaponSlot[slot][0];
}
this.pickedWeapons[this.classIdx][slot] = weaponItem;
}
calculateKdr() {
this.kdr = Math.floor(this.statsCurrent.kills / Math.max(this.statsCurrent.deaths, 1) * 100) / 100;
this.kdrLifetime = Math.floor(this.statslifetime.kills / Math.max(this.statslifetime.deaths, 1) * 100) / 100;
}
getPickedWeaponInSlot(slot) {
return this.pickedWeapons[this.classIdx][slot];
}
getPrimaryWeapon() {
return this.getPickedWeaponInSlot(Slot.Primary);
}
getSecondaryWeapon() {
return this.getPickedWeaponInSlot(Slot.Secondary);
}
isUpgraded() {
return hasValue(this.upgradeProductId) && !this.upgradeIsExpired;
}
addToInventory(item, autoEquip) {
if (!this.isItemOwned(item)) {
this.inventory.push(item);
}
if (autoEquip === true) {
this.tryEquipItem(item);
}
}
tryEquipItem(item) {
if (this.isItemOwned(item)) {
switch (item.item_type_id) {
case ItemType.Hat:
this.hatItem = item;
break;
case ItemType.Stamp:
this.stampItem = item;
break;
case ItemType.Primary:
if (item.exclusive_for_class !== this.classIdx) {
this.setClass(item.exclusive_for_class);
}
this.pickWeapon(Slot.Primary, item);
break;
case ItemType.Secondary:
this.pickWeapon(Slot.Secondary, item);
break;
case ItemType.Grenade:
this.grenadeItem = item;
break;
case ItemType.Melee:
this.meleeItem = item;
break;
}
}
}
signedIn(firebaseUser2, serverAccountData) {
if (firebaseUser2.uid !== serverAccountData.firebaseId) {
console.log("Firebase user ID does not match account returned from API");
return;
}
this.isAnonymous = firebaseUser2.isAnonymous;
this.isEmailVerified = !this.isAnonymous && serverAccountData.emailVerified;
this.id = serverAccountData.id;
this.firebaseId = serverAccountData.firebaseId;
this.sessionId = serverAccountData.sessionId;
this.session = serverAccountData.session;
this.maskedEmail = serverAccountData.maskedEmail;
this.kills = serverAccountData.kills;
this.deaths = serverAccountData.deaths;
this.streak = serverAccountData.streak;
this.currentBalance = serverAccountData.currentBalance;
this.upgradeProductId = serverAccountData.upgradeProductId;
this.killMultiplier = hasValue(serverAccountData.upgradeMultiplier) ? serverAccountData.upgradeMultiplier : 1;
this.upgradeExpiryDate = hasValue(serverAccountData.upgradeExpiryDate) ? serverAccountData.upgradeExpiryDate : null;
this.upgradeIsExpired = hasValue(serverAccountData.upgradeExpiryDate) ? serverAccountData.upgradeIsExpired : null;
this.hideAds = hasValue(serverAccountData.upgradeAdFree) && !this.upgradeIsExpired ? serverAccountData.upgradeAdFree : false;
this.isSubscriber = serverAccountData.upgradeType === "subscription" && !serverAccountData.upgradeIsExpired ? true : false;
this.upgradeName = serverAccountData.upgradeName;
this.maybeSchoolEmail = serverAccountData.maybeSchoolEmail;
this.subscriptionEnded = serverAccountData.subscriptionEnded;
this.twitchLinked = serverAccountData.twitchLinked;
this.twitchName = serverAccountData.twitchName;
this.contentCreator = serverAccountData.social;
this.setStats(serverAccountData.statsLifetime, serverAccountData.statsCurrent);
this.dateCreated = serverAccountData.dateCreated;
this.accountAge = serverAccountData.accountAge;
this.eggsSpent = serverAccountData.eggsSpent;
this.eggsSpentMonthly = serverAccountData.eggsSpentMonthly;
this.eggsEarnedBalance = this.setEggBalances(this.currentBalance);
G.adminRoles = serverAccountData.adminRoles;
if (hasValue(serverAccountData.ownedItemIds)) {
for (var i2 = 0; i2 < serverAccountData.ownedItemIds.length; i2++) {
var item = G.catalog.findItemById(serverAccountData.ownedItemIds[i2]);
this.inventory.push(item);
}
}
if (this.isUpgraded()) {
G.checkUpgrade();
}
if (this.subscriptionEnded) {
G.vipSubEnded = true;
}
if (serverAccountData.firstSignin) {
G.showSigninBonus = true;
}
this.applyLoadoutObject(serverAccountData.loadout);
this.applyLocalLoadout(serverAccountData.loadout);
sessionRenewalWorker.postMessage({
servicesServer: G.servicesServer,
sessionId: this.sessionId
});
}
convertLoadout(getLoadout) {
if (!getLoadout) {
getLoadout = this.generateLoadoutObject();
}
const theLoadout = {
primaryId: [getLoadout.soldier_primary_item_id, getLoadout.scrambler_primary_item_id, getLoadout.ranger_primary_item_id, getLoadout.eggsploder_primary_item_id, getLoadout.whipper_primary_item_id, getLoadout.crackshot_primary_item_id, getLoadout.trihard_primary_item_id],
secondaryId: [getLoadout.soldier_secondary_item_id, getLoadout.scrambler_secondary_item_id, getLoadout.ranger_secondary_item_id, getLoadout.eggsploder_secondary_item_id, getLoadout.whipper_secondary_item_id, getLoadout.crackshot_secondary_item_id, getLoadout.trihard_secondary_item_id],
hatId: getLoadout.hat_id,
stampId: getLoadout.stamp_id,
grenadeId: getLoadout.grenade_id,
meleeId: getLoadout.melee_id,
classIdx: getLoadout.class_idx,
colorIdx: getLoadout.color
};
return theLoadout;
}
setUpgrade(checkUpgradeResponse) {
this.upgradeProductId = checkUpgradeResponse.upgradeProductId;
this.multiplier = checkUpgradeResponse.multiplier;
this.hideAds = checkUpgradeResponse.hideAds;
this.upgradeIsExpired = checkUpgradeResponse.isExpired;
this.upgradeName = checkUpgradeResponse.upgradeName;
var upgraded = this.isUpgraded();
var expireDate = upgraded ? this.upgradeExpiryDate : null;
if (this.colorIdx >= 7 && !upgraded) {
this.colorIdx = 0;
}
vueApp.setAccountUpgraded(upgraded, expireDate);
}
generateLoadoutObject() {
var loadout = {
classIdx: this.classIdx,
hatId: hasValue(this.hatItem) ? this.hatItem.id : null,
stampId: hasValue(this.stampItem) ? this.stampItem.id : null,
grenadeId: hasValue(this.grenadeItem) ? this.grenadeItem.id : null,
meleeId: hasValue(this.meleeItem) ? this.meleeItem.id : null,
colorIdx: this.colorIdx,
primaryId: this.pickedWeapons.map((w) => {
return w[Slot.Primary].id;
}),
secondaryId: this.pickedWeapons.map((w) => {
return w[Slot.Secondary].id;
})
};
return loadout;
}
applyLocalLoadout(storeData) {
if (!hasValue(storeData)) {
return;
}
let player = storeData;
if (!storeData.hasOwnProperty("primaryId")) {
player = this.convertLoadout(storeData);
}
let lsLoadout = {
items: player,
kills: this.kills ? this.kills : 0,
deaths: this.deaths ? this.deaths : 0,
kdr: this.kdr ? this.kdr : 0,
streak: this.streak ? this.streak : 0,
balance: this._currentBalance
};
localStore.setItem("localLoadOut", JSON.stringify(lsLoadout));
}
applyLoadoutObject(loadout) {
if (hasValue(loadout)) {
if (loadout.classIdx !== void 0 && loadout.classIdx !== null) {
this.setClass(loadout.classIdx);
}
var outer = this;
var trySetPickedWeapon = function(weaponId, classIdx, slot) {
var weaponItem = G.catalog.forClass[classIdx].forWeaponSlot[slot][0];
if (hasValue(weaponId)) {
let item = G.catalog.findItemById(weaponId);
if (item)
weaponItem = item;
}
outer.pickedWeapons[classIdx][slot] = weaponItem;
};
for (var c = 0; c < CharClass.length; c++) {
trySetPickedWeapon(loadout.primaryId[c], c, Slot.Primary);
trySetPickedWeapon(loadout.secondaryId[c], c, Slot.Secondary);
}
if (hasValue(loadout.hatId)) {
var hatItem = G.catalog.findItemById(loadout.hatId);
if (!this.isItemOwned(hatItem)) {
this.hatItem = null;
}
this.hatItem = hatItem;
}
if (hasValue(loadout.stampId)) {
var stampItem = G.catalog.findItemById(loadout.stampId);
if (!this.isItemOwned(stampItem)) {
this.stampItem = null;
}
this.stampItem = stampItem;
}
if (hasValue(loadout.grenadeId)) {
var grenadeItem = G.catalog.findItemById(loadout.grenadeId);
if (!this.isItemOwned(grenadeItem)) {
grenadeItem = G.catalog.findItemById(16e3);
}
this.grenadeItem = grenadeItem;
}
if (hasValue(loadout.meleeId)) {
var meleeItem = G.catalog.findItemById(loadout.meleeId);
if (!this.isItemOwned(meleeItem)) {
meleeItem = G.catalog.findItemById(15e3);
}
this.meleeItem = meleeItem;
}
if (hasValue(loadout.colorIdx)) {
this.colorIdx = loadout.colorIdx;
if (this.colorIdx >= 7 && this.isUpgraded() === false) {
this.colorIdx = 0;
}
}
}
G.resetPaperDoll();
}
applyRandomLoadout() {
let hats = G.catalog.hats.filter((i2) => i2.price === 0 && i2.unlock === "default");
let stamps = G.catalog.stamps.filter((i2) => i2.price === 0 && i2.unlock === "default");
let hatId = hats[Math.randomInt(0, hats.length)].id;
let stampId = stamps[Math.randomInt(0, stamps.length)].id;
this.hatItem = G.catalog.findItemById(hatId);
this.stampItem = G.catalog.findItemById(stampId);
this.colorIdx = Math.randomInt(0, 7);
let loadout = this.generateLoadoutObject();
loadout.hatId = hatId;
loadout.stampId = stampId;
loadout.color = this.colorIdx;
this.applyLocalLoadout(loadout);
setTimeout(() => this.applyLoadoutObject(loadout), 0);
}
getEquippedItems() {
return {
[ItemType.Primary]: this.pickedWeapons[this.classIdx][Slot.Primary],
[ItemType.Secondary]: this.pickedWeapons[this.classIdx][Slot.Secondary],
[ItemType.Hat]: this.hatItem,
[ItemType.Stamp]: this.stampItem,
[ItemType.Grenade]: this.grenadeItem,
[ItemType.Melee]: this.meleeItem
//[ItemType.Color]: this.colorIdx
};
}
syncToServer(callback) {
var loadout = this.generateLoadoutObject();
G.api_saveLoadout(loadout, callback);
if (loadout !== null)
this.applyLocalLoadout(loadout);
}
setEggBalances(balance) {
this.currentBalance = balance;
this.eggsEarnedBalance = this.eggsSpent + this.currentBalance;
}
setStats(lifetime, current) {
this.statsLifetime = lifetime;
this.statsCurrent = current;
}
};
// src/client/hitMarkers.mjs
var HitMarker = class {
constructor(scene) {
this.mesh_ = new G.BABYLON.Mesh("hitMarker", scene);
this.mesh_.updatable = true;
this.mesh_.hasVertexAlpha = true;
this.mesh_.layerMask = 536870912;
this.mesh_.visibility = 0.2;
this.positions = [
1,
2.5,
0,
// 0 Lower-right
0,
3,
0,
// 1 Top
-1,
2.5,
0
// 2 Lower-left
];
var indices = [0, 1, 2];
this.colors = new Array(12).fill(0);
this.colors[0] = 1;
this.colors[4] = 1;
this.colors[8] = 1;
this.colors[7] = 1;
var vertexData = new G.BABYLON.VertexData();
vertexData.positions = this.positions;
vertexData.indices = indices;
vertexData.colors = this.colors;
vertexData.applyToMesh(this.mesh_, true);
this.mesh_.material = scene.getMaterialByName("ui");
return this.mesh_;
}
};
var HitMarkers = class {
constructor(scene) {
this.container = new G.BABYLON.TransformNode("hitMarkers", scene);
this.container.layerMask = 536870912;
this.markers = [];
for (let i2 = 0; i2 < 4; i2++) {
let m = new HitMarker(scene);
m.parent = this.container;
this.markers.push({
mesh: m,
angle: 0
});
}
}
show() {
this.container.setEnabled(true);
}
hide() {
this.container.setEnabled(false);
}
resize() {
let scale = G.engine.getRenderHeight() * 0.1;
this.container.scaling.x = scale;
this.container.scaling.y = scale;
}
update(delta, yaw) {
if (!this.container.isEnabled())
return;
this.container.rotation.z = yaw;
for (let m of this.markers) {
if (m.mesh.visibility > 0) {
m.mesh.visibility = Math.max(0, m.mesh.visibility - 0.06 * delta);
let scale = Math.max(1, m.mesh.scaling.x - 0.01 * delta);
m.mesh.scaling.x = scale;
m.mesh.scaling.y = scale;
}
}
}
hit(dx, dz) {
if (this.container.visibility === 0)
return;
let toAngle = -Math.atan2(dx, -dz);
let angle = -Math.radRange(toAngle);
let marker = void 0;
for (let m of this.markers) {
if (m.mesh.visibility === 0) {
marker = m;
break;
}
}
if (!marker) {
let closestAngle = 1e3;
for (let m of this.markers) {
let diff = Math.abs(Math.radRange(m.angle - angle));
if (diff < closestAngle) {
closestAngle = diff;
marker = m;
}
}
}
marker.angle = angle;
marker.mesh.scaling.x = 1.1;
marker.mesh.scaling.y = 1.1;
marker.mesh.visibility = 5;
marker.mesh.rotation.z = angle;
}
};
// temp/shellshock.js
var __decorate = function(e2, t, r, c) {
var o, f = arguments.length, n = f < 3 ? t : null === c ? c = Object.getOwnPropertyDescriptor(t, r) : c;
if ("object" == typeof Reflect && "function" == typeof Reflect.decorate)
n = Reflect.decorate(e2, t, r, c);
else
for (var l = e2.length - 1; l >= 0; l--)
(o = e2[l]) && (n = (f < 3 ? o(n) : f > 3 ? o(t, r, n) : o(t, r)) || n);
return f > 3 && n && Object.defineProperty(t, r, n), n;
};
var __extends = function() {
var t = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(t2, o) {
t2.__proto__ = o;
} || function(t2, o) {
for (var n in o)
o.hasOwnProperty(n) && (t2[n] = o[n]);
};
return function(o, n) {
function r() {
this.constructor = o;
}
t(o, n), o.prototype = null === n ? Object.create(n) : (r.prototype = n.prototype, new r());
};
}();
var BABYLON;
(function(BABYLON2) {
var EffectFallbacks = (
/** @class */
function() {
function EffectFallbacks2() {
this._defines = {};
this._currentRank = 32;
this._maxRank = -1;
}
EffectFallbacks2.prototype.unBindMesh = function() {
this._mesh = null;
};
EffectFallbacks2.prototype.addFallback = function(rank, define) {
if (!this._defines[rank]) {
if (rank < this._currentRank) {
this._currentRank = rank;
}
if (rank > this._maxRank) {
this._maxRank = rank;
}
this._defines[rank] = new Array();
}
this._defines[rank].push(define);
};
EffectFallbacks2.prototype.addCPUSkinningFallback = function(rank, mesh2) {
this._mesh = mesh2;
if (rank < this._currentRank) {
this._currentRank = rank;
}
if (rank > this._maxRank) {
this._maxRank = rank;
}
};
Object.defineProperty(EffectFallbacks2.prototype, "isMoreFallbacks", {
/**
* Checks to see if more fallbacks are still availible.
*/
get: function() {
return this._currentRank <= this._maxRank;
},
enumerable: true,
configurable: true
});
EffectFallbacks2.prototype.reduce = function(currentDefines, effect) {
if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
this._mesh.computeBonesUsingShaders = false;
currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
effect._bonesComputationForcedToCPU = true;
var scene = this._mesh.getScene();
for (var index = 0; index < scene.meshes.length; index++) {
var otherMesh = scene.meshes[index];
if (!otherMesh.material) {
continue;
}
if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
continue;
}
if (otherMesh.material.getEffect() === effect) {
otherMesh.computeBonesUsingShaders = false;
} else if (otherMesh.subMeshes) {
for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
var subMeshEffect = subMesh.effect;
if (subMeshEffect === effect) {
otherMesh.computeBonesUsingShaders = false;
break;
}
}
}
}
} else {
var currentFallbacks = this._defines[this._currentRank];
if (currentFallbacks) {
for (var index = 0; index < currentFallbacks.length; index++) {
currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
}
}
this._currentRank++;
}
return currentDefines;
};
return EffectFallbacks2;
}()
);
BABYLON2.EffectFallbacks = EffectFallbacks;
var EffectCreationOptions = (
/** @class */
function() {
function EffectCreationOptions2() {
}
return EffectCreationOptions2;
}()
);
BABYLON2.EffectCreationOptions = EffectCreationOptions;
var Effect = (
/** @class */
function() {
function Effect2(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
if (samplers === void 0) {
samplers = null;
}
if (defines === void 0) {
defines = null;
}
if (fallbacks === void 0) {
fallbacks = null;
}
if (onCompiled === void 0) {
onCompiled = null;
}
if (onError === void 0) {
onError = null;
}
var _this = this;
this.uniqueId = 0;
this.onCompileObservable = new BABYLON2.Observable();
this.onErrorObservable = new BABYLON2.Observable();
this._bonesComputationForcedToCPU = false;
this._uniformBuffersNames = {};
this._isReady = false;
this._compilationError = "";
this.name = baseName;
if (attributesNamesOrOptions.attributes) {
var options = attributesNamesOrOptions;
this._engine = uniformsNamesOrEngine;
this._attributesNames = options.attributes;
this._uniformsNames = options.uniformsNames.concat(options.samplers);
this._samplers = options.samplers.slice();
this.defines = options.defines;
this.onError = options.onError;
this.onCompiled = options.onCompiled;
this._fallbacks = options.fallbacks;
this._indexParameters = options.indexParameters;
this._transformFeedbackVaryings = options.transformFeedbackVaryings;
if (options.uniformBuffersNames) {
for (var i2 = 0; i2 < options.uniformBuffersNames.length; i2++) {
this._uniformBuffersNames[options.uniformBuffersNames[i2]] = i2;
}
}
} else {
this._engine = engine;
this.defines = defines;
this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
this._samplers = samplers ? samplers.slice() : [];
this._attributesNames = attributesNamesOrOptions;
this.onError = onError;
this.onCompiled = onCompiled;
this._indexParameters = indexParameters;
this._fallbacks = fallbacks;
}
this.uniqueId = Effect2._uniqueIdSeed++;
var vertexSource;
var fragmentSource;
if (baseName.vertexElement) {
vertexSource = document.getElementById(baseName.vertexElement);
if (!vertexSource) {
vertexSource = baseName.vertexElement;
}
} else {
vertexSource = baseName.vertex || baseName;
}
if (baseName.fragmentElement) {
fragmentSource = document.getElementById(baseName.fragmentElement);
if (!fragmentSource) {
fragmentSource = baseName.fragmentElement;
}
} else {
fragmentSource = baseName.fragment || baseName;
}
this._loadVertexShader(vertexSource, function(vertexCode) {
_this._processIncludes(vertexCode, function(vertexCodeWithIncludes) {
_this._processShaderConversion(vertexCodeWithIncludes, false, function(migratedVertexCode) {
_this._loadFragmentShader(fragmentSource, function(fragmentCode) {
_this._processIncludes(fragmentCode, function(fragmentCodeWithIncludes) {
_this._processShaderConversion(fragmentCodeWithIncludes, true, function(migratedFragmentCode) {
if (baseName) {
var vertex = baseName.vertexElement || baseName.vertex || baseName;
var fragment = baseName.fragmentElement || baseName.fragment || baseName;
_this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
_this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
} else {
_this._vertexSourceCode = migratedVertexCode;
_this._fragmentSourceCode = migratedFragmentCode;
}
_this._prepareEffect();
});
});
});
});
});
});
}
Object.defineProperty(Effect2.prototype, "onBindObservable", {
/**
* Observable that will be called when effect is bound.
*/
get: function() {
if (!this._onBindObservable) {
this._onBindObservable = new BABYLON2.Observable();
}
return this._onBindObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Effect2.prototype, "key", {
/**
* Unique key for this effect
*/
get: function() {
return this._key;
},
enumerable: true,
configurable: true
});
Effect2.prototype.isReady = function() {
return this._isReady;
};
Effect2.prototype.getEngine = function() {
return this._engine;
};
Effect2.prototype.getProgram = function() {
return this._program;
};
Effect2.prototype.getAttributesNames = function() {
return this._attributesNames;
};
Effect2.prototype.getAttributeLocation = function(index) {
return this._attributes[index];
};
Effect2.prototype.getAttributeLocationByName = function(name) {
var index = this._attributesNames.indexOf(name);
return this._attributes[index];
};
Effect2.prototype.getAttributesCount = function() {
return this._attributes.length;
};
Effect2.prototype.getUniformIndex = function(uniformName) {
return this._uniformsNames.indexOf(uniformName);
};
Effect2.prototype.getUniform = function(uniformName) {
return this._uniforms[this._uniformsNames.indexOf(uniformName)];
};
Effect2.prototype.getSamplers = function() {
return this._samplers;
};
Effect2.prototype.getCompilationError = function() {
return this._compilationError;
};
Effect2.prototype.executeWhenCompiled = function(func) {
if (this.isReady()) {
func(this);
return;
}
this.onCompileObservable.add(function(effect) {
func(effect);
});
};
Effect2.prototype._loadVertexShader = function(vertex, callback) {
if (BABYLON2.Tools.IsWindowObjectExist()) {
if (vertex instanceof HTMLElement) {
var vertexCode = BABYLON2.Tools.GetDOMTextContent(vertex);
callback(vertexCode);
return;
}
}
if (vertex.substr(0, 7) === "base64:") {
var vertexBinary = window.atob(vertex.substr(7));
callback(vertexBinary);
return;
}
if (Effect2.ShadersStore[vertex + "VertexShader"]) {
callback(Effect2.ShadersStore[vertex + "VertexShader"]);
return;
}
var vertexShaderUrl;
if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
vertexShaderUrl = vertex;
} else {
vertexShaderUrl = BABYLON2.Engine.ShadersRepository + vertex;
}
this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
};
Effect2.prototype._loadFragmentShader = function(fragment, callback) {
if (BABYLON2.Tools.IsWindowObjectExist()) {
if (fragment instanceof HTMLElement) {
var fragmentCode = BABYLON2.Tools.GetDOMTextContent(fragment);
callback(fragmentCode);
return;
}
}
if (fragment.substr(0, 7) === "base64:") {
var fragmentBinary = window.atob(fragment.substr(7));
callback(fragmentBinary);
return;
}
if (Effect2.ShadersStore[fragment + "PixelShader"]) {
callback(Effect2.ShadersStore[fragment + "PixelShader"]);
return;
}
if (Effect2.ShadersStore[fragment + "FragmentShader"]) {
callback(Effect2.ShadersStore[fragment + "FragmentShader"]);
return;
}
var fragmentShaderUrl;
if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
fragmentShaderUrl = fragment;
} else {
fragmentShaderUrl = BABYLON2.Engine.ShadersRepository + fragment;
}
this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
};
Effect2.prototype._dumpShadersSource = function(vertexCode, fragmentCode, defines) {
var shaderVersion = this._engine.webGLVersion > 1 ? "#version 300 es\n#define WEBGL2 \n" : "";
var prefix = shaderVersion + (defines ? defines + "\n" : "");
vertexCode = prefix + vertexCode;
fragmentCode = prefix + fragmentCode;
var i2 = 2;
var regex = /\n/gm;
var formattedVertexCode = "\n1 " + vertexCode.replace(regex, function() {
return "\n" + i2++ + " ";
});
i2 = 2;
var formattedFragmentCode = "\n1 " + fragmentCode.replace(regex, function() {
return "\n" + i2++ + " ";
});
if (this.name.vertexElement) {
BABYLON2.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
BABYLON2.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
} else if (this.name.vertex) {
BABYLON2.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
BABYLON2.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
} else {
BABYLON2.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
BABYLON2.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
}
};
Effect2.prototype._processShaderConversion = function(sourceCode, isFragment, callback) {
var preparedSourceCode = this._processPrecision(sourceCode);
if (this._engine.webGLVersion == 1) {
callback(preparedSourceCode);
return;
}
if (preparedSourceCode.indexOf("#version 3") !== -1) {
callback(preparedSourceCode.replace("#version 300 es", ""));
return;
}
var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
var result = preparedSourceCode.replace(regex, "");
result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
result = result.replace(/attribute[ \t]/g, "in ");
result = result.replace(/[ \t]attribute/g, " in");
if (isFragment) {
result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
result = result.replace(/texture2D\s*\(/g, "texture(");
result = result.replace(/textureCube\s*\(/g, "texture(");
result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
result = result.replace(/gl_FragColor/g, "glFragColor");
result = result.replace(/gl_FragData/g, "glFragData");
result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
}
callback(result);
};
Effect2.prototype._processIncludes = function(sourceCode, callback) {
var _this = this;
var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
var match = regex.exec(sourceCode);
var returnValue = new String(sourceCode);
while (match != null) {
var includeFile = match[1];
if (includeFile.indexOf("__decl__") !== -1) {
includeFile = includeFile.replace(/__decl__/, "");
if (this._engine.supportsUniformBuffers) {
includeFile = includeFile.replace(/Vertex/, "Ubo");
includeFile = includeFile.replace(/Fragment/, "Ubo");
}
includeFile = includeFile + "Declaration";
}
if (Effect2.IncludesShadersStore[includeFile]) {
var includeContent = Effect2.IncludesShadersStore[includeFile];
if (match[2]) {
var splits = match[3].split(",");
for (var index = 0; index < splits.length; index += 2) {
var source = new RegExp(splits[index], "g");
var dest = splits[index + 1];
includeContent = includeContent.replace(source, dest);
}
}
if (match[4]) {
var indexString = match[5];
if (indexString.indexOf("..") !== -1) {
var indexSplits = indexString.split("..");
var minIndex = parseInt(indexSplits[0]);
var maxIndex = parseInt(indexSplits[1]);
var sourceIncludeContent = includeContent.slice(0);
includeContent = "";
if (isNaN(maxIndex)) {
maxIndex = this._indexParameters[indexSplits[1]];
}
for (var i2 = minIndex; i2 < maxIndex; i2++) {
if (!this._engine.supportsUniformBuffers) {
sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function(str, p1) {
return p1 + "{X}";
});
}
includeContent += sourceIncludeContent.replace(/\{X\}/g, i2.toString()) + "\n";
}
} else {
if (!this._engine.supportsUniformBuffers) {
includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function(str, p1) {
return p1 + "{X}";
});
}
includeContent = includeContent.replace(/\{X\}/g, indexString);
}
}
returnValue = returnValue.replace(match[0], includeContent);
} else {
var includeShaderUrl = BABYLON2.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
this._engine._loadFile(includeShaderUrl, function(fileContent) {
Effect2.IncludesShadersStore[includeFile] = fileContent;
_this._processIncludes(returnValue, callback);
});
return;
}
match = regex.exec(sourceCode);
}
callback(returnValue);
};
Effect2.prototype._processPrecision = function(source) {
if (source.indexOf("precision highp float") === -1) {
if (!this._engine.getCaps().highPrecisionShaderSupported) {
source = "precision mediump float;\n" + source;
} else {
source = "precision highp float;\n" + source;
}
} else {
if (!this._engine.getCaps().highPrecisionShaderSupported) {
source = source.replace("precision highp float", "precision mediump float");
}
}
return source;
};
Effect2.prototype._rebuildProgram = function(vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
var _this = this;
this._isReady = false;
this._vertexSourceCodeOverride = vertexSourceCode;
this._fragmentSourceCodeOverride = fragmentSourceCode;
this.onError = function(effect, error) {
if (onError) {
onError(error);
}
};
this.onCompiled = function() {
var scenes = _this.getEngine().scenes;
for (var i2 = 0; i2 < scenes.length; i2++) {
scenes[i2].markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
}
if (onCompiled) {
onCompiled(_this._program);
}
};
this._fallbacks = null;
this._prepareEffect();
};
Effect2.prototype.getSpecificUniformLocations = function(names) {
var engine = this._engine;
return engine.getUniforms(this._program, names);
};
Effect2.prototype._prepareEffect = function() {
var attributesNames = this._attributesNames;
var defines = this.defines;
var fallbacks = this._fallbacks;
this._valueCache = {};
var previousProgram = this._program;
try {
var engine = this._engine;
if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, void 0, this._transformFeedbackVaryings);
} else {
this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, void 0, this._transformFeedbackVaryings);
}
this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
if (engine.supportsUniformBuffers) {
for (var name in this._uniformBuffersNames) {
this.bindUniformBlock(name, this._uniformBuffersNames[name]);
}
}
this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
this._attributes = engine.getAttributes(this._program, attributesNames);
var index;
for (index = 0; index < this._samplers.length; index++) {
var sampler = this.getUniform(this._samplers[index]);
if (sampler == null) {
this._samplers.splice(index, 1);
index--;
}
}
engine.bindSamplers(this);
this._compilationError = "";
this._isReady = true;
if (this.onCompiled) {
this.onCompiled(this);
}
this.onCompileObservable.notifyObservers(this);
this.onCompileObservable.clear();
if (this._fallbacks) {
this._fallbacks.unBindMesh();
}
if (previousProgram) {
this.getEngine()._deleteProgram(previousProgram);
}
} catch (e2) {
this._compilationError = e2.message;
BABYLON2.Tools.Error("Unable to compile effect:");
BABYLON2.Tools.Error("Uniforms: " + this._uniformsNames.map(function(uniform) {
return " " + uniform;
}));
BABYLON2.Tools.Error("Attributes: " + attributesNames.map(function(attribute) {
return " " + attribute;
}));
BABYLON2.Tools.Error("Error: " + this._compilationError);
if (previousProgram) {
this._program = previousProgram;
this._isReady = true;
if (this.onError) {
this.onError(this, this._compilationError);
}
this.onErrorObservable.notifyObservers(this);
}
if (fallbacks && fallbacks.isMoreFallbacks) {
BABYLON2.Tools.Error("Trying next fallback.");
this.defines = fallbacks.reduce(this.defines, this);
this._prepareEffect();
} else {
if (this.onError) {
this.onError(this, this._compilationError);
}
this.onErrorObservable.notifyObservers(this);
this.onErrorObservable.clear();
if (this._fallbacks) {
this._fallbacks.unBindMesh();
}
}
}
};
Object.defineProperty(Effect2.prototype, "isSupported", {
/**
* Checks if the effect is supported. (Must be called after compilation)
*/
get: function() {
return this._compilationError === "";
},
enumerable: true,
configurable: true
});
Effect2.prototype._bindTexture = function(channel, texture) {
this._engine._bindTexture(this._samplers.indexOf(channel), texture);
};
Effect2.prototype.setTexture = function(channel, texture) {
this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
};
Effect2.prototype.setDepthStencilTexture = function(channel, texture) {
this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
};
Effect2.prototype.setTextureArray = function(channel, textures) {
if (this._samplers.indexOf(channel + "Ex") === -1) {
var initialPos = this._samplers.indexOf(channel);
for (var index = 1; index < textures.length; index++) {
this._samplers.splice(initialPos + index, 0, channel + "Ex");
}
}
this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
};
Effect2.prototype.setTextureFromPostProcess = function(channel, postProcess) {
this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
};
Effect2.prototype.setTextureFromPostProcessOutput = function(channel, postProcess) {
this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
};
Effect2.prototype._cacheMatrix = function(uniformName, matrix) {
var cache = this._valueCache[uniformName];
var flag = matrix.updateFlag;
if (cache !== void 0 && cache === flag) {
return false;
}
this._valueCache[uniformName] = flag;
return true;
};
Effect2.prototype._cacheFloat2 = function(uniformName, x, y) {
var cache = this._valueCache[uniformName];
if (!cache) {
cache = [x, y];
this._valueCache[uniformName] = cache;
return true;
}
var changed = false;
if (cache[0] !== x) {
cache[0] = x;
changed = true;
}
if (cache[1] !== y) {
cache[1] = y;
changed = true;
}
return changed;
};
Effect2.prototype._cacheFloat3 = function(uniformName, x, y, z) {
var cache = this._valueCache[uniformName];
if (!cache) {
cache = [x, y, z];
this._valueCache[uniformName] = cache;
return true;
}
var changed = false;
if (cache[0] !== x) {
cache[0] = x;
changed = true;
}
if (cache[1] !== y) {
cache[1] = y;
changed = true;
}
if (cache[2] !== z) {
cache[2] = z;
changed = true;
}
return changed;
};
Effect2.prototype._cacheFloat4 = function(uniformName, x, y, z, w) {
var cache = this._valueCache[uniformName];
if (!cache) {
cache = [x, y, z, w];
this._valueCache[uniformName] = cache;
return true;
}
var changed = false;
if (cache[0] !== x) {
cache[0] = x;
changed = true;
}
if (cache[1] !== y) {
cache[1] = y;
changed = true;
}
if (cache[2] !== z) {
cache[2] = z;
changed = true;
}
if (cache[3] !== w) {
cache[3] = w;
changed = true;
}
return changed;
};
Effect2.prototype.bindUniformBuffer = function(buffer, name) {
var bufferName = this._uniformBuffersNames[name];
if (bufferName === void 0 || Effect2._baseCache[bufferName] === buffer) {
return;
}
Effect2._baseCache[bufferName] = buffer;
this._engine.bindUniformBufferBase(buffer, bufferName);
};
Effect2.prototype.bindUniformBlock = function(blockName, index) {
this._engine.bindUniformBlock(this._program, blockName, index);
};
Effect2.prototype.setInt = function(uniformName, value) {
var cache = this._valueCache[uniformName];
if (cache !== void 0 && cache === value) {
return this;
}
this._valueCache[uniformName] = value;
this._engine.setInt(this.getUniform(uniformName), value);
return this;
};
Effect2.prototype.setIntArray = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setIntArray2 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray2(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setIntArray3 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray3(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setIntArray4 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setIntArray4(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setFloatArray = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setFloatArray2 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray2(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setFloatArray3 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray3(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setFloatArray4 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setFloatArray4(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setArray = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setArray2 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray2(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setArray3 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray3(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setArray4 = function(uniformName, array) {
this._valueCache[uniformName] = null;
this._engine.setArray4(this.getUniform(uniformName), array);
return this;
};
Effect2.prototype.setMatrices = function(uniformName, matrices) {
if (!matrices) {
return this;
}
this._valueCache[uniformName] = null;
this._engine.setMatrices(this.getUniform(uniformName), matrices);
return this;
};
Effect2.prototype.setMatrix = function(uniformName, matrix) {
if (this._cacheMatrix(uniformName, matrix)) {
this._engine.setMatrix(this.getUniform(uniformName), matrix);
}
return this;
};
Effect2.prototype.setMatrix3x3 = function(uniformName, matrix) {
this._valueCache[uniformName] = null;
this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
return this;
};
Effect2.prototype.setMatrix2x2 = function(uniformName, matrix) {
this._valueCache[uniformName] = null;
this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
return this;
};
Effect2.prototype.setFloat = function(uniformName, value) {
var cache = this._valueCache[uniformName];
if (cache !== void 0 && cache === value) {
return this;
}
this._valueCache[uniformName] = value;
this._engine.setFloat(this.getUniform(uniformName), value);
return this;
};
Effect2.prototype.setBool = function(uniformName, bool) {
var cache = this._valueCache[uniformName];
if (cache !== void 0 && cache === bool) {
return this;
}
this._valueCache[uniformName] = bool;
this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
return this;
};
Effect2.prototype.setVector2 = function(uniformName, vector2) {
if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
}
return this;
};
Effect2.prototype.setFloat2 = function(uniformName, x, y) {
if (this._cacheFloat2(uniformName, x, y)) {
this._engine.setFloat2(this.getUniform(uniformName), x, y);
}
return this;
};
Effect2.prototype.setVector3 = function(uniformName, vector3) {
if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
}
return this;
};
Effect2.prototype.setFloat3 = function(uniformName, x, y, z) {
if (this._cacheFloat3(uniformName, x, y, z)) {
this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
}
return this;
};
Effect2.prototype.setVector4 = function(uniformName, vector4) {
if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
}
return this;
};
Effect2.prototype.setFloat4 = function(uniformName, x, y, z, w) {
if (this._cacheFloat4(uniformName, x, y, z, w)) {
this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
}
return this;
};
Effect2.prototype.setColor3 = function(uniformName, color3) {
if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
this._engine.setColor3(this.getUniform(uniformName), color3);
}
return this;
};
Effect2.prototype.setColor4 = function(uniformName, color3, alpha) {
if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
}
return this;
};
Effect2.prototype.setDirectColor4 = function(uniformName, color4) {
if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
this._engine.setDirectColor4(this.getUniform(uniformName), color4);
}
return this;
};
Effect2.RegisterShader = function(name, pixelShader, vertexShader) {
if (pixelShader) {
Effect2.ShadersStore[name + "PixelShader"] = pixelShader;
}
if (vertexShader) {
Effect2.ShadersStore[name + "VertexShader"] = vertexShader;
}
};
Effect2.ResetCache = function() {
Effect2._baseCache = {};
};
Effect2._uniqueIdSeed = 0;
Effect2._baseCache = {};
Effect2.ShadersStore = {};
Effect2.IncludesShadersStore = {};
return Effect2;
}()
);
BABYLON2.Effect = Effect;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var KeyboardEventTypes = (
/** @class */
function() {
function KeyboardEventTypes2() {
}
KeyboardEventTypes2.KEYDOWN = 1;
KeyboardEventTypes2.KEYUP = 2;
return KeyboardEventTypes2;
}()
);
BABYLON2.KeyboardEventTypes = KeyboardEventTypes;
var KeyboardInfo = (
/** @class */
function() {
function KeyboardInfo2(type, event) {
this.type = type;
this.event = event;
}
return KeyboardInfo2;
}()
);
BABYLON2.KeyboardInfo = KeyboardInfo;
var KeyboardInfoPre = (
/** @class */
function(_super) {
__extends(KeyboardInfoPre2, _super);
function KeyboardInfoPre2(type, event) {
var _this = _super.call(this, type, event) || this;
_this.type = type;
_this.event = event;
_this.skipOnPointerObservable = false;
return _this;
}
return KeyboardInfoPre2;
}(KeyboardInfo)
);
BABYLON2.KeyboardInfoPre = KeyboardInfoPre;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PointerEventTypes = (
/** @class */
function() {
function PointerEventTypes2() {
}
PointerEventTypes2.POINTERDOWN = 1;
PointerEventTypes2.POINTERUP = 2;
PointerEventTypes2.POINTERMOVE = 4;
PointerEventTypes2.POINTERWHEEL = 8;
PointerEventTypes2.POINTERPICK = 16;
PointerEventTypes2.POINTERTAP = 32;
PointerEventTypes2.POINTERDOUBLETAP = 64;
return PointerEventTypes2;
}()
);
BABYLON2.PointerEventTypes = PointerEventTypes;
var PointerInfoBase = (
/** @class */
function() {
function PointerInfoBase2(type, event) {
this.type = type;
this.event = event;
}
return PointerInfoBase2;
}()
);
BABYLON2.PointerInfoBase = PointerInfoBase;
var PointerInfoPre = (
/** @class */
function(_super) {
__extends(PointerInfoPre2, _super);
function PointerInfoPre2(type, event, localX, localY) {
var _this = _super.call(this, type, event) || this;
_this.ray = null;
_this.skipOnPointerObservable = false;
_this.localPosition = new BABYLON2.Vector2(localX, localY);
return _this;
}
return PointerInfoPre2;
}(PointerInfoBase)
);
BABYLON2.PointerInfoPre = PointerInfoPre;
var PointerInfo = (
/** @class */
function(_super) {
__extends(PointerInfo2, _super);
function PointerInfo2(type, event, pickInfo) {
var _this = _super.call(this, type, event) || this;
_this.pickInfo = pickInfo;
return _this;
}
return PointerInfo2;
}(PointerInfoBase)
);
BABYLON2.PointerInfo = PointerInfo;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.ToGammaSpace = 1 / 2.2;
BABYLON2.ToLinearSpace = 2.2;
BABYLON2.Epsilon = 1e-3;
var Color3 = (
/** @class */
function() {
function Color32(r, g, b2) {
if (r === void 0) {
r = 0;
}
if (g === void 0) {
g = 0;
}
if (b2 === void 0) {
b2 = 0;
}
this.r = r;
this.g = g;
this.b = b2;
}
Color32.prototype.toString = function() {
return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
};
Color32.prototype.getClassName = function() {
return "Color3";
};
Color32.prototype.getHashCode = function() {
var hash = this.r || 0;
hash = hash * 397 ^ (this.g || 0);
hash = hash * 397 ^ (this.b || 0);
return hash;
};
Color32.prototype.toArray = function(array, index) {
if (index === void 0) {
index = 0;
}
array[index] = this.r;
array[index + 1] = this.g;
array[index + 2] = this.b;
return this;
};
Color32.prototype.toColor4 = function(alpha) {
if (alpha === void 0) {
alpha = 1;
}
return new Color4(this.r, this.g, this.b, alpha);
};
Color32.prototype.asArray = function() {
var result = new Array();
this.toArray(result, 0);
return result;
};
Color32.prototype.toLuminance = function() {
return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
};
Color32.prototype.multiply = function(otherColor) {
return new Color32(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
};
Color32.prototype.multiplyToRef = function(otherColor, result) {
result.r = this.r * otherColor.r;
result.g = this.g * otherColor.g;
result.b = this.b * otherColor.b;
return this;
};
Color32.prototype.equals = function(otherColor) {
return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
};
Color32.prototype.equalsFloats = function(r, g, b2) {
return this.r === r && this.g === g && this.b === b2;
};
Color32.prototype.scale = function(scale) {
return new Color32(this.r * scale, this.g * scale, this.b * scale);
};
Color32.prototype.scaleToRef = function(scale, result) {
result.r = this.r * scale;
result.g = this.g * scale;
result.b = this.b * scale;
return this;
};
Color32.prototype.scaleAndAddToRef = function(scale, result) {
result.r += this.r * scale;
result.g += this.g * scale;
result.b += this.b * scale;
return this;
};
Color32.prototype.clampToRef = function(min, max, result) {
if (min === void 0) {
min = 0;
}
if (max === void 0) {
max = 1;
}
result.r = BABYLON2.Scalar.Clamp(this.r, min, max);
result.g = BABYLON2.Scalar.Clamp(this.g, min, max);
result.b = BABYLON2.Scalar.Clamp(this.b, min, max);
return this;
};
Color32.prototype.add = function(otherColor) {
return new Color32(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
};
Color32.prototype.addToRef = function(otherColor, result) {
result.r = this.r + otherColor.r;
result.g = this.g + otherColor.g;
result.b = this.b + otherColor.b;
return this;
};
Color32.prototype.subtract = function(otherColor) {
return new Color32(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
};
Color32.prototype.subtractToRef = function(otherColor, result) {
result.r = this.r - otherColor.r;
result.g = this.g - otherColor.g;
result.b = this.b - otherColor.b;
return this;
};
Color32.prototype.clone = function() {
return new Color32(this.r, this.g, this.b);
};
Color32.prototype.copyFrom = function(source) {
this.r = source.r;
this.g = source.g;
this.b = source.b;
return this;
};
Color32.prototype.copyFromFloats = function(r, g, b2) {
this.r = r;
this.g = g;
this.b = b2;
return this;
};
Color32.prototype.set = function(r, g, b2) {
return this.copyFromFloats(r, g, b2);
};
Color32.prototype.toHexString = function() {
var intR = this.r * 255 | 0;
var intG = this.g * 255 | 0;
var intB = this.b * 255 | 0;
return "#" + BABYLON2.Scalar.ToHex(intR) + BABYLON2.Scalar.ToHex(intG) + BABYLON2.Scalar.ToHex(intB);
};
Color32.prototype.toLinearSpace = function() {
var convertedColor = new Color32();
this.toLinearSpaceToRef(convertedColor);
return convertedColor;
};
Color32.prototype.toLinearSpaceToRef = function(convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON2.ToLinearSpace);
convertedColor.g = Math.pow(this.g, BABYLON2.ToLinearSpace);
convertedColor.b = Math.pow(this.b, BABYLON2.ToLinearSpace);
return this;
};
Color32.prototype.toGammaSpace = function() {
var convertedColor = new Color32();
this.toGammaSpaceToRef(convertedColor);
return convertedColor;
};
Color32.prototype.toGammaSpaceToRef = function(convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON2.ToGammaSpace);
convertedColor.g = Math.pow(this.g, BABYLON2.ToGammaSpace);
convertedColor.b = Math.pow(this.b, BABYLON2.ToGammaSpace);
return this;
};
Color32.FromHexString = function(hex) {
if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
return new Color32(0, 0, 0);
}
var r = parseInt(hex.substring(1, 3), 16);
var g = parseInt(hex.substring(3, 5), 16);
var b2 = parseInt(hex.substring(5, 7), 16);
return Color32.FromInts(r, g, b2);
};
Color32.FromArray = function(array, offset) {
if (offset === void 0) {
offset = 0;
}
return new Color32(array[offset], array[offset + 1], array[offset + 2]);
};
Color32.FromInts = function(r, g, b2) {
return new Color32(r / 255, g / 255, b2 / 255);
};
Color32.Lerp = function(start, end, amount) {
var result = new Color32(0, 0, 0);
Color32.LerpToRef(start, end, amount, result);
return result;
};
Color32.LerpToRef = function(left, right, amount, result) {
result.r = left.r + (right.r - left.r) * amount;
result.g = left.g + (right.g - left.g) * amount;
result.b = left.b + (right.b - left.b) * amount;
};
Color32.Red = function() {
return new Color32(1, 0, 0);
};
Color32.Green = function() {
return new Color32(0, 1, 0);
};
Color32.Blue = function() {
return new Color32(0, 0, 1);
};
Color32.Black = function() {
return new Color32(0, 0, 0);
};
Color32.White = function() {
return new Color32(1, 1, 1);
};
Color32.Purple = function() {
return new Color32(0.5, 0, 0.5);
};
Color32.Magenta = function() {
return new Color32(1, 0, 1);
};
Color32.Yellow = function() {
return new Color32(1, 1, 0);
};
Color32.Gray = function() {
return new Color32(0.5, 0.5, 0.5);
};
Color32.Teal = function() {
return new Color32(0, 1, 1);
};
Color32.Random = function() {
return new Color32(Math.random(), Math.random(), Math.random());
};
return Color32;
}()
);
BABYLON2.Color3 = Color3;
var Color4 = (
/** @class */
function() {
function Color42(r, g, b2, a) {
if (r === void 0) {
r = 0;
}
if (g === void 0) {
g = 0;
}
if (b2 === void 0) {
b2 = 0;
}
if (a === void 0) {
a = 1;
}
this.r = r;
this.g = g;
this.b = b2;
this.a = a;
}
Color42.prototype.addInPlace = function(right) {
this.r += right.r;
this.g += right.g;
this.b += right.b;
this.a += right.a;
return this;
};
Color42.prototype.asArray = function() {
var result = new Array();
this.toArray(result, 0);
return result;
};
Color42.prototype.toArray = function(array, index) {
if (index === void 0) {
index = 0;
}
array[index] = this.r;
array[index + 1] = this.g;
array[index + 2] = this.b;
array[index + 3] = this.a;
return this;
};
Color42.prototype.add = function(right) {
return new Color42(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
};
Color42.prototype.subtract = function(right) {
return new Color42(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
};
Color42.prototype.subtractToRef = function(right, result) {
result.r = this.r - right.r;
result.g = this.g - right.g;
result.b = this.b - right.b;
result.a = this.a - right.a;
return this;
};
Color42.prototype.scale = function(scale) {
return new Color42(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
};
Color42.prototype.scaleToRef = function(scale, result) {
result.r = this.r * scale;
result.g = this.g * scale;
result.b = this.b * scale;
result.a = this.a * scale;
return this;
};
Color42.prototype.scaleAndAddToRef = function(scale, result) {
result.r += this.r * scale;
result.g += this.g * scale;
result.b += this.b * scale;
result.a += this.a * scale;
return this;
};
Color42.prototype.clampToRef = function(min, max, result) {
if (min === void 0) {
min = 0;
}
if (max === void 0) {
max = 1;
}
result.r = BABYLON2.Scalar.Clamp(this.r, min, max);
result.g = BABYLON2.Scalar.Clamp(this.g, min, max);
result.b = BABYLON2.Scalar.Clamp(this.b, min, max);
result.a = BABYLON2.Scalar.Clamp(this.a, min, max);
return this;
};
Color42.prototype.multiply = function(color) {
return new Color42(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
};
Color42.prototype.multiplyToRef = function(color, result) {
result.r = this.r * color.r;
result.g = this.g * color.g;
result.b = this.b * color.b;
result.a = this.a * color.a;
return result;
};
Color42.prototype.toString = function() {
return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
};
Color42.prototype.getClassName = function() {
return "Color4";
};
Color42.prototype.getHashCode = function() {
var hash = this.r || 0;
hash = hash * 397 ^ (this.g || 0);
hash = hash * 397 ^ (this.b || 0);
hash = hash * 397 ^ (this.a || 0);
return hash;
};
Color42.prototype.clone = function() {
return new Color42(this.r, this.g, this.b, this.a);
};
Color42.prototype.copyFrom = function(source) {
this.r = source.r;
this.g = source.g;
this.b = source.b;
this.a = source.a;
return this;
};
Color42.prototype.copyFromFloats = function(r, g, b2, a) {
this.r = r;
this.g = g;
this.b = b2;
this.a = a;
return this;
};
Color42.prototype.set = function(r, g, b2, a) {
return this.copyFromFloats(r, g, b2, a);
};
Color42.prototype.toHexString = function() {
var intR = this.r * 255 | 0;
var intG = this.g * 255 | 0;
var intB = this.b * 255 | 0;
var intA = this.a * 255 | 0;
return "#" + BABYLON2.Scalar.ToHex(intR) + BABYLON2.Scalar.ToHex(intG) + BABYLON2.Scalar.ToHex(intB) + BABYLON2.Scalar.ToHex(intA);
};
Color42.prototype.toLinearSpace = function() {
var convertedColor = new Color42();
this.toLinearSpaceToRef(convertedColor);
return convertedColor;
};
Color42.prototype.toLinearSpaceToRef = function(convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON2.ToLinearSpace);
convertedColor.g = Math.pow(this.g, BABYLON2.ToLinearSpace);
convertedColor.b = Math.pow(this.b, BABYLON2.ToLinearSpace);
convertedColor.a = this.a;
return this;
};
Color42.prototype.toGammaSpace = function() {
var convertedColor = new Color42();
this.toGammaSpaceToRef(convertedColor);
return convertedColor;
};
Color42.prototype.toGammaSpaceToRef = function(convertedColor) {
convertedColor.r = Math.pow(this.r, BABYLON2.ToGammaSpace);
convertedColor.g = Math.pow(this.g, BABYLON2.ToGammaSpace);
convertedColor.b = Math.pow(this.b, BABYLON2.ToGammaSpace);
convertedColor.a = this.a;
return this;
};
Color42.FromHexString = function(hex) {
if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
return new Color42(0, 0, 0, 0);
}
var r = parseInt(hex.substring(1, 3), 16);
var g = parseInt(hex.substring(3, 5), 16);
var b2 = parseInt(hex.substring(5, 7), 16);
var a = parseInt(hex.substring(7, 9), 16);
return Color42.FromInts(r, g, b2, a);
};
Color42.Lerp = function(left, right, amount) {
var result = new Color42(0, 0, 0, 0);
Color42.LerpToRef(left, right, amount, result);
return result;
};
Color42.LerpToRef = function(left, right, amount, result) {
result.r = left.r + (right.r - left.r) * amount;
result.g = left.g + (right.g - left.g) * amount;
result.b = left.b + (right.b - left.b) * amount;
result.a = left.a + (right.a - left.a) * amount;
};
Color42.FromColor3 = function(color3, alpha) {
if (alpha === void 0) {
alpha = 1;
}
return new Color42(color3.r, color3.g, color3.b, alpha);
};
Color42.FromArray = function(array, offset) {
if (offset === void 0) {
offset = 0;
}
return new Color42(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
};
Color42.FromInts = function(r, g, b2, a) {
return new Color42(r / 255, g / 255, b2 / 255, a / 255);
};
Color42.CheckColors4 = function(colors, count) {
if (colors.length === count * 3) {
var colors4 = [];
for (var index = 0; index < colors.length; index += 3) {
var newIndex = index / 3 * 4;
colors4[newIndex] = colors[index];
colors4[newIndex + 1] = colors[index + 1];
colors4[newIndex + 2] = colors[index + 2];
colors4[newIndex + 3] = 1;
}
return colors4;
}
return colors;
};
return Color42;
}()
);
BABYLON2.Color4 = Color4;
var Vector2 = (
/** @class */
function() {
function Vector22(x, y) {
if (x === void 0) {
x = 0;
}
if (y === void 0) {
y = 0;
}
this.x = x;
this.y = y;
}
Vector22.prototype.toString = function() {
return "{X: " + this.x + " Y:" + this.y + "}";
};
Vector22.prototype.getClassName = function() {
return "Vector2";
};
Vector22.prototype.getHashCode = function() {
var hash = this.x || 0;
hash = hash * 397 ^ (this.y || 0);
return hash;
};
Vector22.prototype.toArray = function(array, index) {
if (index === void 0) {
index = 0;
}
array[index] = this.x;
array[index + 1] = this.y;
return this;
};
Vector22.prototype.asArray = function() {
var result = new Array();
this.toArray(result, 0);
return result;
};
Vector22.prototype.copyFrom = function(source) {
this.x = source.x;
this.y = source.y;
return this;
};
Vector22.prototype.copyFromFloats = function(x, y) {
this.x = x;
this.y = y;
return this;
};
Vector22.prototype.set = function(x, y) {
return this.copyFromFloats(x, y);
};
Vector22.prototype.add = function(otherVector) {
return new Vector22(this.x + otherVector.x, this.y + otherVector.y);
};
Vector22.prototype.addToRef = function(otherVector, result) {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
return this;
};
Vector22.prototype.addInPlace = function(otherVector) {
this.x += otherVector.x;
this.y += otherVector.y;
return this;
};
Vector22.prototype.addVector3 = function(otherVector) {
return new Vector22(this.x + otherVector.x, this.y + otherVector.y);
};
Vector22.prototype.subtract = function(otherVector) {
return new Vector22(this.x - otherVector.x, this.y - otherVector.y);
};
Vector22.prototype.subtractToRef = function(otherVector, result) {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
return this;
};
Vector22.prototype.subtractInPlace = function(otherVector) {
this.x -= otherVector.x;
this.y -= otherVector.y;
return this;
};
Vector22.prototype.multiplyInPlace = function(otherVector) {
this.x *= otherVector.x;
this.y *= otherVector.y;
return this;
};
Vector22.prototype.multiply = function(otherVector) {
return new Vector22(this.x * otherVector.x, this.y * otherVector.y);
};
Vector22.prototype.multiplyToRef = function(otherVector, result) {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
return this;
};
Vector22.prototype.multiplyByFloats = function(x, y) {
return new Vector22(this.x * x, this.y * y);
};
Vector22.prototype.divide = function(otherVector) {
return new Vector22(this.x / otherVector.x, this.y / otherVector.y);
};
Vector22.prototype.divideToRef = function(otherVector, result) {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
return this;
};
Vector22.prototype.divideInPlace = function(otherVector) {
return this.divideToRef(otherVector, this);
};
Vector22.prototype.negate = function() {
return new Vector22(-this.x, -this.y);
};
Vector22.prototype.scaleInPlace = function(scale) {
this.x *= scale;
this.y *= scale;
return this;
};
Vector22.prototype.scale = function(scale) {
var result = new Vector22(0, 0);
this.scaleToRef(scale, result);
return result;
};
Vector22.prototype.scaleToRef = function(scale, result) {
result.x = this.x * scale;
result.y = this.y * scale;
return this;
};
Vector22.prototype.scaleAndAddToRef = function(scale, result) {
result.x += this.x * scale;
result.y += this.y * scale;
return this;
};
Vector22.prototype.equals = function(otherVector) {
return otherVector && this.x === otherVector.x && this.y === otherVector.y;
};
Vector22.prototype.equalsWithEpsilon = function(otherVector, epsilon) {
if (epsilon === void 0) {
epsilon = BABYLON2.Epsilon;
}
return otherVector && BABYLON2.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON2.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
};
Vector22.prototype.floor = function() {
return new Vector22(Math.floor(this.x), Math.floor(this.y));
};
Vector22.prototype.fract = function() {
return new Vector22(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
};
Vector22.prototype.length = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
Vector22.prototype.lengthSquared = function() {
return this.x * this.x + this.y * this.y;
};
Vector22.prototype.normalize = function() {
var len = this.length();
if (len === 0) {
return this;
}
var num = 1 / len;
this.x *= num;
this.y *= num;
return this;
};
Vector22.prototype.clone = function() {
return new Vector22(this.x, this.y);
};
Vector22.Zero = function() {
return new Vector22(0, 0);
};
Vector22.One = function() {
return new Vector22(1, 1);
};
Vector22.FromArray = function(array, offset) {
if (offset === void 0) {
offset = 0;
}
return new Vector22(array[offset], array[offset + 1]);
};
Vector22.FromArrayToRef = function(array, offset, result) {
result.x = array[offset];
result.y = array[offset + 1];
};
Vector22.CatmullRom = function(value1, value2, value3, value4, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var x = 0.5 * (2 * value2.x + (-value1.x + value3.x) * amount + (2 * value1.x - 5 * value2.x + 4 * value3.x - value4.x) * squared + (-value1.x + 3 * value2.x - 3 * value3.x + value4.x) * cubed);
var y = 0.5 * (2 * value2.y + (-value1.y + value3.y) * amount + (2 * value1.y - 5 * value2.y + 4 * value3.y - value4.y) * squared + (-value1.y + 3 * value2.y - 3 * value3.y + value4.y) * cubed);
return new Vector22(x, y);
};
Vector22.Clamp = function(value, min, max) {
var x = value.x;
x = x > max.x ? max.x : x;
x = x < min.x ? min.x : x;
var y = value.y;
y = y > max.y ? max.y : y;
y = y < min.y ? min.y : y;
return new Vector22(x, y);
};
Vector22.Hermite = function(value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = 2 * cubed - 3 * squared + 1;
var part2 = -2 * cubed + 3 * squared;
var part3 = cubed - 2 * squared + amount;
var part4 = cubed - squared;
var x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;
var y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;
return new Vector22(x, y);
};
Vector22.Lerp = function(start, end, amount) {
var x = start.x + (end.x - start.x) * amount;
var y = start.y + (end.y - start.y) * amount;
return new Vector22(x, y);
};
Vector22.Dot = function(left, right) {
return left.x * right.x + left.y * right.y;
};
Vector22.Normalize = function(vector) {
var newVector = vector.clone();
newVector.normalize();
return newVector;
};
Vector22.Minimize = function(left, right) {
var x = left.x < right.x ? left.x : right.x;
var y = left.y < right.y ? left.y : right.y;
return new Vector22(x, y);
};
Vector22.Maximize = function(left, right) {
var x = left.x > right.x ? left.x : right.x;
var y = left.y > right.y ? left.y : right.y;
return new Vector22(x, y);
};
Vector22.Transform = function(vector, transformation) {
var r = Vector22.Zero();
Vector22.TransformToRef(vector, transformation, r);
return r;
};
Vector22.TransformToRef = function(vector, transformation, result) {
var x = vector.x * transformation.m[0] + vector.y * transformation.m[4] + transformation.m[12];
var y = vector.x * transformation.m[1] + vector.y * transformation.m[5] + transformation.m[13];
result.x = x;
result.y = y;
};
Vector22.PointInTriangle = function(p, p0, p1, p2) {
var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
var sign = a < 0 ? -1 : 1;
var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
return s > 0 && t > 0 && s + t < 2 * a * sign;
};
Vector22.Distance = function(value1, value2) {
return Math.sqrt(Vector22.DistanceSquared(value1, value2));
};
Vector22.DistanceSquared = function(value1, value2) {
var x = value1.x - value2.x;
var y = value1.y - value2.y;
return x * x + y * y;
};
Vector22.Center = function(value1, value2) {
var center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
};
Vector22.DistanceOfPointFromSegment = function(p, segA, segB) {
var l2 = Vector22.DistanceSquared(segA, segB);
if (l2 === 0) {
return Vector22.Distance(p, segA);
}
var v = segB.subtract(segA);
var t = Math.max(0, Math.min(1, Vector22.Dot(p.subtract(segA), v) / l2));
var proj = segA.add(v.multiplyByFloats(t, t));
return Vector22.Distance(p, proj);
};
return Vector22;
}()
);
BABYLON2.Vector2 = Vector2;
var Vector3 = (
/** @class */
function() {
function Vector32(x, y, z) {
if (x === void 0) {
x = 0;
}
if (y === void 0) {
y = 0;
}
if (z === void 0) {
z = 0;
}
this.x = x;
this.y = y;
this.z = z;
}
Vector32.prototype.toString = function() {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
};
Vector32.prototype.getClassName = function() {
return "Vector3";
};
Vector32.prototype.getHashCode = function() {
var hash = this.x || 0;
hash = hash * 397 ^ (this.y || 0);
hash = hash * 397 ^ (this.z || 0);
return hash;
};
Vector32.prototype.asArray = function() {
var result = [];
this.toArray(result, 0);
return result;
};
Vector32.prototype.toArray = function(array, index) {
if (index === void 0) {
index = 0;
}
array[index] = this.x;
array[index + 1] = this.y;
array[index + 2] = this.z;
return this;
};
Vector32.prototype.toQuaternion = function() {
return BABYLON2.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
};
Vector32.prototype.addInPlace = function(otherVector) {
this.x += otherVector.x;
this.y += otherVector.y;
this.z += otherVector.z;
return this;
};
Vector32.prototype.add = function(otherVector) {
return new Vector32(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
};
Vector32.prototype.addToRef = function(otherVector, result) {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
result.z = this.z + otherVector.z;
return this;
};
Vector32.prototype.subtractInPlace = function(otherVector) {
this.x -= otherVector.x;
this.y -= otherVector.y;
this.z -= otherVector.z;
return this;
};
Vector32.prototype.subtract = function(otherVector) {
return new Vector32(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
};
Vector32.prototype.subtractToRef = function(otherVector, result) {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
result.z = this.z - otherVector.z;
return this;
};
Vector32.prototype.subtractFromFloats = function(x, y, z) {
return new Vector32(this.x - x, this.y - y, this.z - z);
};
Vector32.prototype.subtractFromFloatsToRef = function(x, y, z, result) {
result.x = this.x - x;
result.y = this.y - y;
result.z = this.z - z;
return this;
};
Vector32.prototype.negate = function() {
return new Vector32(-this.x, -this.y, -this.z);
};
Vector32.prototype.scaleInPlace = function(scale) {
this.x *= scale;
this.y *= scale;
this.z *= scale;
return this;
};
Vector32.prototype.scale = function(scale) {
return new Vector32(this.x * scale, this.y * scale, this.z * scale);
};
Vector32.prototype.scaleToRef = function(scale, result) {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
return this;
};
Vector32.prototype.scaleAndAddToRef = function(scale, result) {
result.x += this.x * scale;
result.y += this.y * scale;
result.z += this.z * scale;
return this;
};
Vector32.prototype.equals = function(otherVector) {
return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
};
Vector32.prototype.equalsWithEpsilon = function(otherVector, epsilon) {
if (epsilon === void 0) {
epsilon = BABYLON2.Epsilon;
}
return otherVector && BABYLON2.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON2.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON2.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
};
Vector32.prototype.equalsToFloats = function(x, y, z) {
return this.x === x && this.y === y && this.z === z;
};
Vector32.prototype.multiplyInPlace = function(otherVector) {
this.x *= otherVector.x;
this.y *= otherVector.y;
this.z *= otherVector.z;
return this;
};
Vector32.prototype.multiply = function(otherVector) {
return new Vector32(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
};
Vector32.prototype.multiplyToRef = function(otherVector, result) {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
result.z = this.z * otherVector.z;
return this;
};
Vector32.prototype.multiplyByFloats = function(x, y, z) {
return new Vector32(this.x * x, this.y * y, this.z * z);
};
Vector32.prototype.divide = function(otherVector) {
return new Vector32(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
};
Vector32.prototype.divideToRef = function(otherVector, result) {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
result.z = this.z / otherVector.z;
return this;
};
Vector32.prototype.divideInPlace = function(otherVector) {
return this.divideToRef(otherVector, this);
};
Vector32.prototype.minimizeInPlace = function(other) {
return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
};
Vector32.prototype.maximizeInPlace = function(other) {
return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
};
Vector32.prototype.minimizeInPlaceFromFloats = function(x, y, z) {
if (x < this.x) {
this.x = x;
}
if (y < this.y) {
this.y = y;
}
if (z < this.z) {
this.z = z;
}
return this;
};
Vector32.prototype.maximizeInPlaceFromFloats = function(x, y, z) {
if (x > this.x) {
this.x = x;
}
if (y > this.y) {
this.y = y;
}
if (z > this.z) {
this.z = z;
}
return this;
};
Object.defineProperty(Vector32.prototype, "isNonUniform", {
/**
* Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
*/
get: function() {
var absX = Math.abs(this.x);
var absY = Math.abs(this.y);
if (absX !== absY) {
return true;
}
var absZ = Math.abs(this.z);
if (absX !== absZ) {
return true;
}
if (absY !== absZ) {
return true;
}
return false;
},
enumerable: true,
configurable: true
});
Vector32.prototype.floor = function() {
return new Vector32(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
};
Vector32.prototype.fract = function() {
return new Vector32(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
};
Vector32.prototype.length = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
Vector32.prototype.lengthSquared = function() {
return this.x * this.x + this.y * this.y + this.z * this.z;
};
Vector32.prototype.normalize = function() {
var len = this.length();
if (len === 0 || len === 1) {
return this;
}
var num = 1 / len;
this.x *= num;
this.y *= num;
this.z *= num;
return this;
};
Vector32.prototype.normalizeToNew = function() {
var normalized = new Vector32(0, 0, 0);
this.normalizeToRef(normalized);
return normalized;
};
Vector32.prototype.normalizeToRef = function(reference) {
var len = this.length();
if (len === 0 || len === 1) {
reference.set(this.x, this.y, this.z);
return reference;
}
var scale = 1 / len;
this.scaleToRef(scale, reference);
return reference;
};
Vector32.prototype.clone = function() {
return new Vector32(this.x, this.y, this.z);
};
Vector32.prototype.copyFrom = function(source) {
this.x = source.x;
this.y = source.y;
this.z = source.z;
return this;
};
Vector32.prototype.copyFromFloats = function(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
return this;
};
Vector32.prototype.set = function(x, y, z) {
return this.copyFromFloats(x, y, z);
};
Vector32.GetClipFactor = function(vector0, vector1, axis, size) {
var d0 = Vector32.Dot(vector0, axis) - size;
var d1 = Vector32.Dot(vector1, axis) - size;
var s = d0 / (d0 - d1);
return s;
};
Vector32.GetAngleBetweenVectors = function(vector0, vector1, normal) {
var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
var dot = Vector32.Dot(v0, v1);
var n = MathTmp.Vector3[3];
Vector32.CrossToRef(v0, v1, n);
if (Vector32.Dot(n, normal) > 0) {
return Math.acos(dot);
}
return -Math.acos(dot);
};
Vector32.FromArray = function(array, offset) {
if (!offset) {
offset = 0;
}
return new Vector32(array[offset], array[offset + 1], array[offset + 2]);
};
Vector32.FromFloatArray = function(array, offset) {
return Vector32.FromArray(array, offset);
};
Vector32.FromArrayToRef = function(array, offset, result) {
result.x = array[offset];
result.y = array[offset + 1];
result.z = array[offset + 2];
};
Vector32.FromFloatArrayToRef = function(array, offset, result) {
return Vector32.FromArrayToRef(array, offset, result);
};
Vector32.FromFloatsToRef = function(x, y, z, result) {
result.x = x;
result.y = y;
result.z = z;
};
Vector32.Zero = function() {
return new Vector32(0, 0, 0);
};
Vector32.One = function() {
return new Vector32(1, 1, 1);
};
Vector32.Up = function() {
return new Vector32(0, 1, 0);
};
Vector32.Down = function() {
return new Vector32(0, -1, 0);
};
Vector32.Forward = function() {
return new Vector32(0, 0, 1);
};
Vector32.Backward = function() {
return new Vector32(0, 0, -1);
};
Vector32.Right = function() {
return new Vector32(1, 0, 0);
};
Vector32.Left = function() {
return new Vector32(-1, 0, 0);
};
Vector32.TransformCoordinates = function(vector, transformation) {
var result = Vector32.Zero();
Vector32.TransformCoordinatesToRef(vector, transformation, result);
return result;
};
Vector32.TransformCoordinatesToRef = function(vector, transformation, result) {
var x = vector.x * transformation.m[0] + vector.y * transformation.m[4] + vector.z * transformation.m[8] + transformation.m[12];
var y = vector.x * transformation.m[1] + vector.y * transformation.m[5] + vector.z * transformation.m[9] + transformation.m[13];
var z = vector.x * transformation.m[2] + vector.y * transformation.m[6] + vector.z * transformation.m[10] + transformation.m[14];
var w = vector.x * transformation.m[3] + vector.y * transformation.m[7] + vector.z * transformation.m[11] + transformation.m[15];
result.x = x / w;
result.y = y / w;
result.z = z / w;
};
Vector32.TransformCoordinatesFromFloatsToRef = function(x, y, z, transformation, result) {
var rx = x * transformation.m[0] + y * transformation.m[4] + z * transformation.m[8] + transformation.m[12];
var ry = x * transformation.m[1] + y * transformation.m[5] + z * transformation.m[9] + transformation.m[13];
var rz = x * transformation.m[2] + y * transformation.m[6] + z * transformation.m[10] + transformation.m[14];
var rw = x * transformation.m[3] + y * transformation.m[7] + z * transformation.m[11] + transformation.m[15];
result.x = rx / rw;
result.y = ry / rw;
result.z = rz / rw;
};
Vector32.TransformNormal = function(vector, transformation) {
var result = Vector32.Zero();
Vector32.TransformNormalToRef(vector, transformation, result);
return result;
};
Vector32.TransformNormalToRef = function(vector, transformation, result) {
var x = vector.x * transformation.m[0] + vector.y * transformation.m[4] + vector.z * transformation.m[8];
var y = vector.x * transformation.m[1] + vector.y * transformation.m[5] + vector.z * transformation.m[9];
var z = vector.x * transformation.m[2] + vector.y * transformation.m[6] + vector.z * transformation.m[10];
result.x = x;
result.y = y;
result.z = z;
};
Vector32.TransformNormalFromFloatsToRef = function(x, y, z, transformation, result) {
result.x = x * transformation.m[0] + y * transformation.m[4] + z * transformation.m[8];
result.y = x * transformation.m[1] + y * transformation.m[5] + z * transformation.m[9];
result.z = x * transformation.m[2] + y * transformation.m[6] + z * transformation.m[10];
};
Vector32.CatmullRom = function(value1, value2, value3, value4, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var x = 0.5 * (2 * value2.x + (-value1.x + value3.x) * amount + (2 * value1.x - 5 * value2.x + 4 * value3.x - value4.x) * squared + (-value1.x + 3 * value2.x - 3 * value3.x + value4.x) * cubed);
var y = 0.5 * (2 * value2.y + (-value1.y + value3.y) * amount + (2 * value1.y - 5 * value2.y + 4 * value3.y - value4.y) * squared + (-value1.y + 3 * value2.y - 3 * value3.y + value4.y) * cubed);
var z = 0.5 * (2 * value2.z + (-value1.z + value3.z) * amount + (2 * value1.z - 5 * value2.z + 4 * value3.z - value4.z) * squared + (-value1.z + 3 * value2.z - 3 * value3.z + value4.z) * cubed);
return new Vector32(x, y, z);
};
Vector32.Clamp = function(value, min, max) {
var x = value.x;
x = x > max.x ? max.x : x;
x = x < min.x ? min.x : x;
var y = value.y;
y = y > max.y ? max.y : y;
y = y < min.y ? min.y : y;
var z = value.z;
z = z > max.z ? max.z : z;
z = z < min.z ? min.z : z;
return new Vector32(x, y, z);
};
Vector32.Hermite = function(value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = 2 * cubed - 3 * squared + 1;
var part2 = -2 * cubed + 3 * squared;
var part3 = cubed - 2 * squared + amount;
var part4 = cubed - squared;
var x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;
var y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;
var z = value1.z * part1 + value2.z * part2 + tangent1.z * part3 + tangent2.z * part4;
return new Vector32(x, y, z);
};
Vector32.Lerp = function(start, end, amount) {
var result = new Vector32(0, 0, 0);
Vector32.LerpToRef(start, end, amount, result);
return result;
};
Vector32.LerpToRef = function(start, end, amount, result) {
result.x = start.x + (end.x - start.x) * amount;
result.y = start.y + (end.y - start.y) * amount;
result.z = start.z + (end.z - start.z) * amount;
};
Vector32.Dot = function(left, right) {
return left.x * right.x + left.y * right.y + left.z * right.z;
};
Vector32.Cross = function(left, right) {
var result = Vector32.Zero();
Vector32.CrossToRef(left, right, result);
return result;
};
Vector32.CrossToRef = function(left, right, result) {
MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
result.copyFrom(MathTmp.Vector3[0]);
};
Vector32.Normalize = function(vector) {
var result = Vector32.Zero();
Vector32.NormalizeToRef(vector, result);
return result;
};
Vector32.NormalizeToRef = function(vector, result) {
result.copyFrom(vector);
result.normalize();
};
Vector32.Project = function(vector, world, transform, viewport) {
var cw = viewport.width;
var ch = viewport.height;
var cx = viewport.x;
var cy = viewport.y;
var viewportMatrix = Vector32._viewportMatrixCache ? Vector32._viewportMatrixCache : Vector32._viewportMatrixCache = new Matrix();
Matrix.FromValuesToRef(cw / 2, 0, 0, 0, 0, -ch / 2, 0, 0, 0, 0, 0.5, 0, cx + cw / 2, ch / 2 + cy, 0.5, 1, viewportMatrix);
var matrix = MathTmp.Matrix[0];
world.multiplyToRef(transform, matrix);
matrix.multiplyToRef(viewportMatrix, matrix);
return Vector32.TransformCoordinates(vector, matrix);
};
Vector32.UnprojectFromTransform = function(source, viewportWidth, viewportHeight, world, transform) {
var matrix = MathTmp.Matrix[0];
world.multiplyToRef(transform, matrix);
matrix.invert();
source.x = source.x / viewportWidth * 2 - 1;
source.y = -(source.y / viewportHeight * 2 - 1);
var vector = Vector32.TransformCoordinates(source, matrix);
var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
if (BABYLON2.Scalar.WithinEpsilon(num, 1)) {
vector = vector.scale(1 / num);
}
return vector;
};
Vector32.Unproject = function(source, viewportWidth, viewportHeight, world, view, projection) {
var result = Vector32.Zero();
Vector32.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
return result;
};
Vector32.UnprojectToRef = function(source, viewportWidth, viewportHeight, world, view, projection, result) {
Vector32.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
};
Vector32.UnprojectFloatsToRef = function(sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
var matrix = MathTmp.Matrix[0];
world.multiplyToRef(view, matrix);
matrix.multiplyToRef(projection, matrix);
matrix.invert();
var screenSource = MathTmp.Vector3[0];
screenSource.x = sourceX / viewportWidth * 2 - 1;
screenSource.y = -(sourceY / viewportHeight * 2 - 1);
screenSource.z = 2 * sourceZ - 1;
Vector32.TransformCoordinatesToRef(screenSource, matrix, result);
var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
if (BABYLON2.Scalar.WithinEpsilon(num, 1)) {
result.scaleInPlace(1 / num);
}
};
Vector32.Minimize = function(left, right) {
var min = left.clone();
min.minimizeInPlace(right);
return min;
};
Vector32.Maximize = function(left, right) {
var max = left.clone();
max.maximizeInPlace(right);
return max;
};
Vector32.Distance = function(value1, value2) {
return Math.sqrt(Vector32.DistanceSquared(value1, value2));
};
Vector32.DistanceSquared = function(value1, value2) {
var x = value1.x - value2.x;
var y = value1.y - value2.y;
var z = value1.z - value2.z;
return x * x + y * y + z * z;
};
Vector32.Center = function(value1, value2) {
var center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
};
Vector32.RotationFromAxis = function(axis1, axis2, axis3) {
var rotation = Vector32.Zero();
Vector32.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
return rotation;
};
Vector32.RotationFromAxisToRef = function(axis1, axis2, axis3, ref) {
var quat = MathTmp.Quaternion[0];
Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
quat.toEulerAnglesToRef(ref);
};
return Vector32;
}()
);
BABYLON2.Vector3 = Vector3;
var Vector4 = (
/** @class */
function() {
function Vector42(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
Vector42.prototype.toString = function() {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
};
Vector42.prototype.getClassName = function() {
return "Vector4";
};
Vector42.prototype.getHashCode = function() {
var hash = this.x || 0;
hash = hash * 397 ^ (this.y || 0);
hash = hash * 397 ^ (this.z || 0);
hash = hash * 397 ^ (this.w || 0);
return hash;
};
Vector42.prototype.asArray = function() {
var result = new Array();
this.toArray(result, 0);
return result;
};
Vector42.prototype.toArray = function(array, index) {
if (index === void 0) {
index = 0;
}
array[index] = this.x;
array[index + 1] = this.y;
array[index + 2] = this.z;
array[index + 3] = this.w;
return this;
};
Vector42.prototype.addInPlace = function(otherVector) {
this.x += otherVector.x;
this.y += otherVector.y;
this.z += otherVector.z;
this.w += otherVector.w;
return this;
};
Vector42.prototype.add = function(otherVector) {
return new Vector42(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
};
Vector42.prototype.addToRef = function(otherVector, result) {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
result.z = this.z + otherVector.z;
result.w = this.w + otherVector.w;
return this;
};
Vector42.prototype.subtractInPlace = function(otherVector) {
this.x -= otherVector.x;
this.y -= otherVector.y;
this.z -= otherVector.z;
this.w -= otherVector.w;
return this;
};
Vector42.prototype.subtract = function(otherVector) {
return new Vector42(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
};
Vector42.prototype.subtractToRef = function(otherVector, result) {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
result.z = this.z - otherVector.z;
result.w = this.w - otherVector.w;
return this;
};
Vector42.prototype.subtractFromFloats = function(x, y, z, w) {
return new Vector42(this.x - x, this.y - y, this.z - z, this.w - w);
};
Vector42.prototype.subtractFromFloatsToRef = function(x, y, z, w, result) {
result.x = this.x - x;
result.y = this.y - y;
result.z = this.z - z;
result.w = this.w - w;
return this;
};
Vector42.prototype.negate = function() {
return new Vector42(-this.x, -this.y, -this.z, -this.w);
};
Vector42.prototype.scaleInPlace = function(scale) {
this.x *= scale;
this.y *= scale;
this.z *= scale;
this.w *= scale;
return this;
};
Vector42.prototype.scale = function(scale) {
return new Vector42(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
};
Vector42.prototype.scaleToRef = function(scale, result) {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
result.w = this.w * scale;
return this;
};
Vector42.prototype.scaleAndAddToRef = function(scale, result) {
result.x += this.x * scale;
result.y += this.y * scale;
result.z += this.z * scale;
result.w += this.w * scale;
return this;
};
Vector42.prototype.equals = function(otherVector) {
return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
};
Vector42.prototype.equalsWithEpsilon = function(otherVector, epsilon) {
if (epsilon === void 0) {
epsilon = BABYLON2.Epsilon;
}
return otherVector && BABYLON2.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON2.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON2.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon) && BABYLON2.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
};
Vector42.prototype.equalsToFloats = function(x, y, z, w) {
return this.x === x && this.y === y && this.z === z && this.w === w;
};
Vector42.prototype.multiplyInPlace = function(otherVector) {
this.x *= otherVector.x;
this.y *= otherVector.y;
this.z *= otherVector.z;
this.w *= otherVector.w;
return this;
};
Vector42.prototype.multiply = function(otherVector) {
return new Vector42(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
};
Vector42.prototype.multiplyToRef = function(otherVector, result) {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
result.z = this.z * otherVector.z;
result.w = this.w * otherVector.w;
return this;
};
Vector42.prototype.multiplyByFloats = function(x, y, z, w) {
return new Vector42(this.x * x, this.y * y, this.z * z, this.w * w);
};
Vector42.prototype.divide = function(otherVector) {
return new Vector42(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
};
Vector42.prototype.divideToRef = function(otherVector, result) {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
result.z = this.z / otherVector.z;
result.w = this.w / otherVector.w;
return this;
};
Vector42.prototype.divideInPlace = function(otherVector) {
return this.divideToRef(otherVector, this);
};
Vector42.prototype.minimizeInPlace = function(other) {
if (other.x < this.x) {
this.x = other.x;
}
if (other.y < this.y) {
this.y = other.y;
}
if (other.z < this.z) {
this.z = other.z;
}
if (other.w < this.w) {
this.w = other.w;
}
return this;
};
Vector42.prototype.maximizeInPlace = function(other) {
if (other.x > this.x) {
this.x = other.x;
}
if (other.y > this.y) {
this.y = other.y;
}
if (other.z > this.z) {
this.z = other.z;
}
if (other.w > this.w) {
this.w = other.w;
}
return this;
};
Vector42.prototype.floor = function() {
return new Vector42(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
};
Vector42.prototype.fract = function() {
return new Vector42(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
};
Vector42.prototype.length = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
};
Vector42.prototype.lengthSquared = function() {
return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
};
Vector42.prototype.normalize = function() {
var len = this.length();
if (len === 0) {
return this;
}
var num = 1 / len;
this.x *= num;
this.y *= num;
this.z *= num;
this.w *= num;
return this;
};
Vector42.prototype.toVector3 = function() {
return new Vector3(this.x, this.y, this.z);
};
Vector42.prototype.clone = function() {
return new Vector42(this.x, this.y, this.z, this.w);
};
Vector42.prototype.copyFrom = function(source) {
this.x = source.x;
this.y = source.y;
this.z = source.z;
this.w = source.w;
return this;
};
Vector42.prototype.copyFromFloats = function(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
};
Vector42.prototype.set = function(x, y, z, w) {
return this.copyFromFloats(x, y, z, w);
};
Vector42.FromArray = function(array, offset) {
if (!offset) {
offset = 0;
}
return new Vector42(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
};
Vector42.FromArrayToRef = function(array, offset, result) {
result.x = array[offset];
result.y = array[offset + 1];
result.z = array[offset + 2];
result.w = array[offset + 3];
};
Vector42.FromFloatArrayToRef = function(array, offset, result) {
Vector42.FromArrayToRef(array, offset, result);
};
Vector42.FromFloatsToRef = function(x, y, z, w, result) {
result.x = x;
result.y = y;
result.z = z;
result.w = w;
};
Vector42.Zero = function() {
return new Vector42(0, 0, 0, 0);
};
Vector42.One = function() {
return new Vector42(1, 1, 1, 1);
};
Vector42.Normalize = function(vector) {
var result = Vector42.Zero();
Vector42.NormalizeToRef(vector, result);
return result;
};
Vector42.NormalizeToRef = function(vector, result) {
result.copyFrom(vector);
result.normalize();
};
Vector42.Minimize = function(left, right) {
var min = left.clone();
min.minimizeInPlace(right);
return min;
};
Vector42.Maximize = function(left, right) {
var max = left.clone();
max.maximizeInPlace(right);
return max;
};
Vector42.Distance = function(value1, value2) {
return Math.sqrt(Vector42.DistanceSquared(value1, value2));
};
Vector42.DistanceSquared = function(value1, value2) {
var x = value1.x - value2.x;
var y = value1.y - value2.y;
var z = value1.z - value2.z;
var w = value1.w - value2.w;
return x * x + y * y + z * z + w * w;
};
Vector42.Center = function(value1, value2) {
var center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
};
Vector42.TransformNormal = function(vector, transformation) {
var result = Vector42.Zero();
Vector42.TransformNormalToRef(vector, transformation, result);
return result;
};
Vector42.TransformNormalToRef = function(vector, transformation, result) {
var x = vector.x * transformation.m[0] + vector.y * transformation.m[4] + vector.z * transformation.m[8];
var y = vector.x * transformation.m[1] + vector.y * transformation.m[5] + vector.z * transformation.m[9];
var z = vector.x * transformation.m[2] + vector.y * transformation.m[6] + vector.z * transformation.m[10];
result.x = x;
result.y = y;
result.z = z;
result.w = vector.w;
};
Vector42.TransformNormalFromFloatsToRef = function(x, y, z, w, transformation, result) {
result.x = x * transformation.m[0] + y * transformation.m[4] + z * transformation.m[8];
result.y = x * transformation.m[1] + y * transformation.m[5] + z * transformation.m[9];
result.z = x * transformation.m[2] + y * transformation.m[6] + z * transformation.m[10];
result.w = w;
};
return Vector42;
}()
);
BABYLON2.Vector4 = Vector4;
var Size = (
/** @class */
function() {
function Size2(width, height) {
this.width = width;
this.height = height;
}
Size2.prototype.toString = function() {
return "{W: " + this.width + ", H: " + this.height + "}";
};
Size2.prototype.getClassName = function() {
return "Size";
};
Size2.prototype.getHashCode = function() {
var hash = this.width || 0;
hash = hash * 397 ^ (this.height || 0);
return hash;
};
Size2.prototype.copyFrom = function(src) {
this.width = src.width;
this.height = src.height;
};
Size2.prototype.copyFromFloats = function(width, height) {
this.width = width;
this.height = height;
return this;
};
Size2.prototype.set = function(width, height) {
return this.copyFromFloats(width, height);
};
Size2.prototype.multiplyByFloats = function(w, h) {
return new Size2(this.width * w, this.height * h);
};
Size2.prototype.clone = function() {
return new Size2(this.width, this.height);
};
Size2.prototype.equals = function(other) {
if (!other) {
return false;
}
return this.width === other.width && this.height === other.height;
};
Object.defineProperty(Size2.prototype, "surface", {
/**
* The surface of the Size : width * height (float).
*/
get: function() {
return this.width * this.height;
},
enumerable: true,
configurable: true
});
Size2.Zero = function() {
return new Size2(0, 0);
};
Size2.prototype.add = function(otherSize) {
var r = new Size2(this.width + otherSize.width, this.height + otherSize.height);
return r;
};
Size2.prototype.subtract = function(otherSize) {
var r = new Size2(this.width - otherSize.width, this.height - otherSize.height);
return r;
};
Size2.Lerp = function(start, end, amount) {
var w = start.width + (end.width - start.width) * amount;
var h = start.height + (end.height - start.height) * amount;
return new Size2(w, h);
};
return Size2;
}()
);
BABYLON2.Size = Size;
var Quaternion = (
/** @class */
function() {
function Quaternion2(x, y, z, w) {
if (x === void 0) {
x = 0;
}
if (y === void 0) {
y = 0;
}
if (z === void 0) {
z = 0;
}
if (w === void 0) {
w = 1;
}
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
Quaternion2.prototype.toString = function() {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
};
Quaternion2.prototype.getClassName = function() {
return "Quaternion";
};
Quaternion2.prototype.getHashCode = function() {
var hash = this.x || 0;
hash = hash * 397 ^ (this.y || 0);
hash = hash * 397 ^ (this.z || 0);
hash = hash * 397 ^ (this.w || 0);
return hash;
};
Quaternion2.prototype.asArray = function() {
return [this.x, this.y, this.z, this.w];
};
Quaternion2.prototype.equals = function(otherQuaternion) {
return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
};
Quaternion2.prototype.clone = function() {
return new Quaternion2(this.x, this.y, this.z, this.w);
};
Quaternion2.prototype.copyFrom = function(other) {
this.x = other.x;
this.y = other.y;
this.z = other.z;
this.w = other.w;
return this;
};
Quaternion2.prototype.copyFromFloats = function(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
};
Quaternion2.prototype.set = function(x, y, z, w) {
return this.copyFromFloats(x, y, z, w);
};
Quaternion2.prototype.add = function(other) {
return new Quaternion2(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
};
Quaternion2.prototype.addInPlace = function(other) {
this.x += other.x;
this.y += other.y;
this.z += other.z;
this.w += other.w;
return this;
};
Quaternion2.prototype.subtract = function(other) {
return new Quaternion2(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
};
Quaternion2.prototype.scale = function(value) {
return new Quaternion2(this.x * value, this.y * value, this.z * value, this.w * value);
};
Quaternion2.prototype.scaleToRef = function(scale, result) {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
result.w = this.w * scale;
return this;
};
Quaternion2.prototype.scaleInPlace = function(value) {
this.x *= value;
this.y *= value;
this.z *= value;
this.w *= value;
return this;
};
Quaternion2.prototype.scaleAndAddToRef = function(scale, result) {
result.x += this.x * scale;
result.y += this.y * scale;
result.z += this.z * scale;
result.w += this.w * scale;
return this;
};
Quaternion2.prototype.multiply = function(q1) {
var result = new Quaternion2(0, 0, 0, 1);
this.multiplyToRef(q1, result);
return result;
};
Quaternion2.prototype.multiplyToRef = function(q1, result) {
var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
result.copyFromFloats(x, y, z, w);
return this;
};
Quaternion2.prototype.multiplyInPlace = function(q1) {
this.multiplyToRef(q1, this);
return this;
};
Quaternion2.prototype.conjugateToRef = function(ref) {
ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
return this;
};
Quaternion2.prototype.conjugateInPlace = function() {
this.x *= -1;
this.y *= -1;
this.z *= -1;
return this;
};
Quaternion2.prototype.conjugate = function() {
var result = new Quaternion2(-this.x, -this.y, -this.z, this.w);
return result;
};
Quaternion2.prototype.length = function() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
};
Quaternion2.prototype.normalize = function() {
var length = 1 / this.length();
this.x *= length;
this.y *= length;
this.z *= length;
this.w *= length;
return this;
};
Quaternion2.prototype.toEulerAngles = function(order) {
if (order === void 0) {
order = "YZX";
}
var result = Vector3.Zero();
this.toEulerAnglesToRef(result, order);
return result;
};
Quaternion2.prototype.toEulerAnglesToRef = function(result, order) {
if (order === void 0) {
order = "YZX";
}
var qz = this.z;
var qx = this.x;
var qy = this.y;
var qw = this.w;
var sqw = qw * qw;
var sqz = qz * qz;
var sqx = qx * qx;
var sqy = qy * qy;
var zAxisY = qy * qz - qx * qw;
var limit = 0.4999999;
if (zAxisY < -limit) {
result.y = 2 * Math.atan2(qy, qw);
result.x = Math.PI / 2;
result.z = 0;
} else if (zAxisY > limit) {
result.y = 2 * Math.atan2(qy, qw);
result.x = -Math.PI / 2;
result.z = 0;
} else {
result.z = Math.atan2(2 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw);
result.x = Math.asin(-2 * (qz * qy - qx * qw));
result.y = Math.atan2(2 * (qz * qx + qy * qw), sqz - sqx - sqy + sqw);
}
return this;
};
Quaternion2.prototype.toRotationMatrix = function(result) {
var xx = this.x * this.x;
var yy = this.y * this.y;
var zz = this.z * this.z;
var xy = this.x * this.y;
var zw = this.z * this.w;
var zx = this.z * this.x;
var yw = this.y * this.w;
var yz = this.y * this.z;
var xw = this.x * this.w;
result.m[0] = 1 - 2 * (yy + zz);
result.m[1] = 2 * (xy + zw);
result.m[2] = 2 * (zx - yw);
result.m[3] = 0;
result.m[4] = 2 * (xy - zw);
result.m[5] = 1 - 2 * (zz + xx);
result.m[6] = 2 * (yz + xw);
result.m[7] = 0;
result.m[8] = 2 * (zx + yw);
result.m[9] = 2 * (yz - xw);
result.m[10] = 1 - 2 * (yy + xx);
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result.m[15] = 1;
result._markAsUpdated();
return this;
};
Quaternion2.prototype.fromRotationMatrix = function(matrix) {
Quaternion2.FromRotationMatrixToRef(matrix, this);
return this;
};
Quaternion2.FromRotationMatrix = function(matrix) {
var result = new Quaternion2();
Quaternion2.FromRotationMatrixToRef(matrix, result);
return result;
};
Quaternion2.FromRotationMatrixToRef = function(matrix, result) {
var data2 = matrix.m;
var m11 = data2[0], m12 = data2[4], m13 = data2[8];
var m21 = data2[1], m22 = data2[5], m23 = data2[9];
var m31 = data2[2], m32 = data2[6], m33 = data2[10];
var trace = m11 + m22 + m33;
var s;
if (trace > 0) {
s = 0.5 / Math.sqrt(trace + 1);
result.w = 0.25 / s;
result.x = (m32 - m23) * s;
result.y = (m13 - m31) * s;
result.z = (m21 - m12) * s;
} else if (m11 > m22 && m11 > m33) {
s = 2 * Math.sqrt(1 + m11 - m22 - m33);
result.w = (m32 - m23) / s;
result.x = 0.25 * s;
result.y = (m12 + m21) / s;
result.z = (m13 + m31) / s;
} else if (m22 > m33) {
s = 2 * Math.sqrt(1 + m22 - m11 - m33);
result.w = (m13 - m31) / s;
result.x = (m12 + m21) / s;
result.y = 0.25 * s;
result.z = (m23 + m32) / s;
} else {
s = 2 * Math.sqrt(1 + m33 - m11 - m22);
result.w = (m21 - m12) / s;
result.x = (m13 + m31) / s;
result.y = (m23 + m32) / s;
result.z = 0.25 * s;
}
};
Quaternion2.Dot = function(left, right) {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
};
Quaternion2.AreClose = function(quat0, quat1) {
var dot = Quaternion2.Dot(quat0, quat1);
return dot >= 0;
};
Quaternion2.Zero = function() {
return new Quaternion2(0, 0, 0, 0);
};
Quaternion2.Inverse = function(q) {
return new Quaternion2(-q.x, -q.y, -q.z, q.w);
};
Quaternion2.Identity = function() {
return new Quaternion2(0, 0, 0, 1);
};
Quaternion2.IsIdentity = function(quaternion) {
return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
};
Quaternion2.RotationAxis = function(axis, angle) {
return Quaternion2.RotationAxisToRef(axis, angle, new Quaternion2());
};
Quaternion2.RotationAxisToRef = function(axis, angle, result) {
var sin = Math.sin(angle / 2);
axis.normalize();
result.w = Math.cos(angle / 2);
result.x = axis.x * sin;
result.y = axis.y * sin;
result.z = axis.z * sin;
return result;
};
Quaternion2.FromArray = function(array, offset) {
if (!offset) {
offset = 0;
}
return new Quaternion2(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
};
Quaternion2.RotationYawPitchRoll = function(yaw, pitch, roll) {
var q = new Quaternion2();
Quaternion2.RotationYawPitchRollToRef(yaw, pitch, roll, q);
return q;
};
Quaternion2.RotationYawPitchRollToRef = function(yaw, pitch, roll, result) {
var halfRoll = roll * 0.5;
var halfPitch = pitch * 0.5;
var halfYaw = yaw * 0.5;
var sinRoll = Math.sin(halfRoll);
var cosRoll = Math.cos(halfRoll);
var sinPitch = Math.sin(halfPitch);
var cosPitch = Math.cos(halfPitch);
var sinYaw = Math.sin(halfYaw);
var cosYaw = Math.cos(halfYaw);
result.x = cosYaw * sinPitch * cosRoll + sinYaw * cosPitch * sinRoll;
result.y = sinYaw * cosPitch * cosRoll - cosYaw * sinPitch * sinRoll;
result.z = cosYaw * cosPitch * sinRoll - sinYaw * sinPitch * cosRoll;
result.w = cosYaw * cosPitch * cosRoll + sinYaw * sinPitch * sinRoll;
};
Quaternion2.RotationAlphaBetaGamma = function(alpha, beta, gamma) {
var result = new Quaternion2();
Quaternion2.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
return result;
};
Quaternion2.RotationAlphaBetaGammaToRef = function(alpha, beta, gamma, result) {
var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
var halfBeta = beta * 0.5;
result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
};
Quaternion2.RotationQuaternionFromAxis = function(axis1, axis2, axis3) {
var quat = new Quaternion2(0, 0, 0, 0);
Quaternion2.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
return quat;
};
Quaternion2.RotationQuaternionFromAxisToRef = function(axis1, axis2, axis3, ref) {
var rotMat = MathTmp.Matrix[0];
Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
Quaternion2.FromRotationMatrixToRef(rotMat, ref);
};
Quaternion2.Slerp = function(left, right, amount) {
var result = Quaternion2.Identity();
Quaternion2.SlerpToRef(left, right, amount, result);
return result;
};
Quaternion2.SlerpToRef = function(left, right, amount, result) {
var num2;
var num3;
var num4 = left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
var flag = false;
if (num4 < 0) {
flag = true;
num4 = -num4;
}
if (num4 > 0.999999) {
num3 = 1 - amount;
num2 = flag ? -amount : amount;
} else {
var num5 = Math.acos(num4);
var num6 = 1 / Math.sin(num5);
num3 = Math.sin((1 - amount) * num5) * num6;
num2 = flag ? -Math.sin(amount * num5) * num6 : Math.sin(amount * num5) * num6;
}
result.x = num3 * left.x + num2 * right.x;
result.y = num3 * left.y + num2 * right.y;
result.z = num3 * left.z + num2 * right.z;
result.w = num3 * left.w + num2 * right.w;
};
Quaternion2.Hermite = function(value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = 2 * cubed - 3 * squared + 1;
var part2 = -2 * cubed + 3 * squared;
var part3 = cubed - 2 * squared + amount;
var part4 = cubed - squared;
var x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4;
var y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4;
var z = value1.z * part1 + value2.z * part2 + tangent1.z * part3 + tangent2.z * part4;
var w = value1.w * part1 + value2.w * part2 + tangent1.w * part3 + tangent2.w * part4;
return new Quaternion2(x, y, z, w);
};
return Quaternion2;
}()
);
BABYLON2.Quaternion = Quaternion;
var Matrix = (
/** @class */
function() {
function Matrix2() {
this._isIdentity = false;
this._isIdentityDirty = true;
this.m = new Float32Array(16);
this._markAsUpdated();
}
Matrix2.prototype._markAsUpdated = function() {
this.updateFlag = Matrix2._updateFlagSeed++;
this._isIdentityDirty = true;
};
Matrix2.prototype.isIdentity = function(considerAsTextureMatrix) {
if (considerAsTextureMatrix === void 0) {
considerAsTextureMatrix = false;
}
if (this._isIdentityDirty) {
this._isIdentityDirty = false;
if (this.m[0] !== 1 || this.m[5] !== 1 || this.m[15] !== 1) {
this._isIdentity = false;
} else if (this.m[1] !== 0 || this.m[2] !== 0 || this.m[3] !== 0 || this.m[4] !== 0 || this.m[6] !== 0 || this.m[7] !== 0 || this.m[8] !== 0 || this.m[9] !== 0 || this.m[11] !== 0 || this.m[12] !== 0 || this.m[13] !== 0 || this.m[14] !== 0) {
this._isIdentity = false;
} else {
this._isIdentity = true;
}
if (!considerAsTextureMatrix && this.m[10] !== 1) {
this._isIdentity = false;
}
}
return this._isIdentity;
};
Matrix2.prototype.determinant = function() {
var temp1 = this.m[10] * this.m[15] - this.m[11] * this.m[14];
var temp2 = this.m[9] * this.m[15] - this.m[11] * this.m[13];
var temp3 = this.m[9] * this.m[14] - this.m[10] * this.m[13];
var temp4 = this.m[8] * this.m[15] - this.m[11] * this.m[12];
var temp5 = this.m[8] * this.m[14] - this.m[10] * this.m[12];
var temp6 = this.m[8] * this.m[13] - this.m[9] * this.m[12];
return this.m[0] * (this.m[5] * temp1 - this.m[6] * temp2 + this.m[7] * temp3) - this.m[1] * (this.m[4] * temp1 - this.m[6] * temp4 + this.m[7] * temp5) + this.m[2] * (this.m[4] * temp2 - this.m[5] * temp4 + this.m[7] * temp6) - this.m[3] * (this.m[4] * temp3 - this.m[5] * temp5 + this.m[6] * temp6);
};
Matrix2.prototype.toArray = function() {
return this.m;
};
Matrix2.prototype.asArray = function() {
return this.toArray();
};
Matrix2.prototype.invert = function() {
this.invertToRef(this);
return this;
};
Matrix2.prototype.reset = function() {
for (var index = 0; index < 16; index++) {
this.m[index] = 0;
}
this._markAsUpdated();
return this;
};
Matrix2.prototype.add = function(other) {
var result = new Matrix2();
this.addToRef(other, result);
return result;
};
Matrix2.prototype.addToRef = function(other, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = this.m[index] + other.m[index];
}
result._markAsUpdated();
return this;
};
Matrix2.prototype.addToSelf = function(other) {
for (var index = 0; index < 16; index++) {
this.m[index] += other.m[index];
}
this._markAsUpdated();
return this;
};
Matrix2.prototype.invertToRef = function(other) {
var l1 = this.m[0];
var l2 = this.m[1];
var l3 = this.m[2];
var l4 = this.m[3];
var l5 = this.m[4];
var l6 = this.m[5];
var l7 = this.m[6];
var l8 = this.m[7];
var l9 = this.m[8];
var l10 = this.m[9];
var l11 = this.m[10];
var l12 = this.m[11];
var l13 = this.m[12];
var l14 = this.m[13];
var l15 = this.m[14];
var l16 = this.m[15];
var l17 = l11 * l16 - l12 * l15;
var l18 = l10 * l16 - l12 * l14;
var l19 = l10 * l15 - l11 * l14;
var l20 = l9 * l16 - l12 * l13;
var l21 = l9 * l15 - l11 * l13;
var l22 = l9 * l14 - l10 * l13;
var l23 = l6 * l17 - l7 * l18 + l8 * l19;
var l24 = -(l5 * l17 - l7 * l20 + l8 * l21);
var l25 = l5 * l18 - l6 * l20 + l8 * l22;
var l26 = -(l5 * l19 - l6 * l21 + l7 * l22);
var l27 = 1 / (l1 * l23 + l2 * l24 + l3 * l25 + l4 * l26);
var l28 = l7 * l16 - l8 * l15;
var l29 = l6 * l16 - l8 * l14;
var l30 = l6 * l15 - l7 * l14;
var l31 = l5 * l16 - l8 * l13;
var l32 = l5 * l15 - l7 * l13;
var l33 = l5 * l14 - l6 * l13;
var l34 = l7 * l12 - l8 * l11;
var l35 = l6 * l12 - l8 * l10;
var l36 = l6 * l11 - l7 * l10;
var l37 = l5 * l12 - l8 * l9;
var l38 = l5 * l11 - l7 * l9;
var l39 = l5 * l10 - l6 * l9;
other.m[0] = l23 * l27;
other.m[4] = l24 * l27;
other.m[8] = l25 * l27;
other.m[12] = l26 * l27;
other.m[1] = -(l2 * l17 - l3 * l18 + l4 * l19) * l27;
other.m[5] = (l1 * l17 - l3 * l20 + l4 * l21) * l27;
other.m[9] = -(l1 * l18 - l2 * l20 + l4 * l22) * l27;
other.m[13] = (l1 * l19 - l2 * l21 + l3 * l22) * l27;
other.m[2] = (l2 * l28 - l3 * l29 + l4 * l30) * l27;
other.m[6] = -(l1 * l28 - l3 * l31 + l4 * l32) * l27;
other.m[10] = (l1 * l29 - l2 * l31 + l4 * l33) * l27;
other.m[14] = -(l1 * l30 - l2 * l32 + l3 * l33) * l27;
other.m[3] = -(l2 * l34 - l3 * l35 + l4 * l36) * l27;
other.m[7] = (l1 * l34 - l3 * l37 + l4 * l38) * l27;
other.m[11] = -(l1 * l35 - l2 * l37 + l4 * l39) * l27;
other.m[15] = (l1 * l36 - l2 * l38 + l3 * l39) * l27;
other._markAsUpdated();
return this;
};
Matrix2.prototype.setTranslationFromFloats = function(x, y, z) {
this.m[12] = x;
this.m[13] = y;
this.m[14] = z;
this._markAsUpdated();
return this;
};
Matrix2.prototype.setTranslation = function(vector3) {
this.m[12] = vector3.x;
this.m[13] = vector3.y;
this.m[14] = vector3.z;
this._markAsUpdated();
return this;
};
Matrix2.prototype.getTranslation = function() {
return new Vector3(this.m[12], this.m[13], this.m[14]);
};
Matrix2.prototype.getTranslationToRef = function(result) {
result.x = this.m[12];
result.y = this.m[13];
result.z = this.m[14];
return this;
};
Matrix2.prototype.removeRotationAndScaling = function() {
this.setRowFromFloats(0, 1, 0, 0, 0);
this.setRowFromFloats(1, 0, 1, 0, 0);
this.setRowFromFloats(2, 0, 0, 1, 0);
return this;
};
Matrix2.prototype.multiply = function(other) {
var result = new Matrix2();
this.multiplyToRef(other, result);
return result;
};
Matrix2.prototype.copyFrom = function(other) {
for (var index = 0; index < 16; index++) {
this.m[index] = other.m[index];
}
this._markAsUpdated();
return this;
};
Matrix2.prototype.copyToArray = function(array, offset) {
if (offset === void 0) {
offset = 0;
}
for (var index = 0; index < 16; index++) {
array[offset + index] = this.m[index];
}
return this;
};
Matrix2.prototype.multiplyToRef = function(other, result) {
this.multiplyToArray(other, result.m, 0);
result._markAsUpdated();
return this;
};
Matrix2.prototype.multiplyToArray = function(other, result, offset) {
var tm0 = this.m[0];
var tm1 = this.m[1];
var tm2 = this.m[2];
var tm3 = this.m[3];
var tm4 = this.m[4];
var tm5 = this.m[5];
var tm6 = this.m[6];
var tm7 = this.m[7];
var tm8 = this.m[8];
var tm9 = this.m[9];
var tm10 = this.m[10];
var tm11 = this.m[11];
var tm12 = this.m[12];
var tm13 = this.m[13];
var tm14 = this.m[14];
var tm15 = this.m[15];
var om0 = other.m[0];
var om1 = other.m[1];
var om2 = other.m[2];
var om3 = other.m[3];
var om4 = other.m[4];
var om5 = other.m[5];
var om6 = other.m[6];
var om7 = other.m[7];
var om8 = other.m[8];
var om9 = other.m[9];
var om10 = other.m[10];
var om11 = other.m[11];
var om12 = other.m[12];
var om13 = other.m[13];
var om14 = other.m[14];
var om15 = other.m[15];
result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
return this;
};
Matrix2.prototype.equals = function(value) {
return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
};
Matrix2.prototype.clone = function() {
return Matrix2.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
};
Matrix2.prototype.getClassName = function() {
return "Matrix";
};
Matrix2.prototype.getHashCode = function() {
var hash = this.m[0] || 0;
for (var i2 = 1; i2 < 16; i2++) {
hash = hash * 397 ^ (this.m[i2] || 0);
}
return hash;
};
Matrix2.prototype.decompose = function(scale, rotation, translation) {
if (translation) {
translation.x = this.m[12];
translation.y = this.m[13];
translation.z = this.m[14];
}
scale = scale || MathTmp.Vector3[0];
scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
if (this.determinant() <= 0) {
scale.y *= -1;
}
if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
if (rotation) {
rotation.x = 0;
rotation.y = 0;
rotation.z = 0;
rotation.w = 1;
}
return false;
}
if (rotation) {
Matrix2.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
}
return true;
};
Matrix2.prototype.getRow = function(index) {
if (index < 0 || index > 3) {
return null;
}
var i2 = index * 4;
return new Vector4(this.m[i2 + 0], this.m[i2 + 1], this.m[i2 + 2], this.m[i2 + 3]);
};
Matrix2.prototype.setRow = function(index, row) {
if (index < 0 || index > 3) {
return this;
}
var i2 = index * 4;
this.m[i2 + 0] = row.x;
this.m[i2 + 1] = row.y;
this.m[i2 + 2] = row.z;
this.m[i2 + 3] = row.w;
this._markAsUpdated();
return this;
};
Matrix2.prototype.transpose = function() {
return Matrix2.Transpose(this);
};
Matrix2.prototype.transposeToRef = function(result) {
Matrix2.TransposeToRef(this, result);
return this;
};
Matrix2.prototype.setRowFromFloats = function(index, x, y, z, w) {
if (index < 0 || index > 3) {
return this;
}
var i2 = index * 4;
this.m[i2 + 0] = x;
this.m[i2 + 1] = y;
this.m[i2 + 2] = z;
this.m[i2 + 3] = w;
this._markAsUpdated();
return this;
};
Matrix2.prototype.scale = function(scale) {
var result = new Matrix2();
this.scaleToRef(scale, result);
return result;
};
Matrix2.prototype.scaleToRef = function(scale, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = this.m[index] * scale;
}
result._markAsUpdated();
return this;
};
Matrix2.prototype.scaleAndAddToRef = function(scale, result) {
for (var index = 0; index < 16; index++) {
result.m[index] += this.m[index] * scale;
}
result._markAsUpdated();
return this;
};
Matrix2.prototype.toNormalMatrix = function(ref) {
this.invertToRef(ref);
ref.transpose();
var m = ref.m;
Matrix2.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
};
Matrix2.prototype.getRotationMatrix = function() {
var result = Matrix2.Identity();
this.getRotationMatrixToRef(result);
return result;
};
Matrix2.prototype.getRotationMatrixToRef = function(result) {
var m = this.m;
var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
if (this.determinant() <= 0) {
sy *= -1;
}
if (sx === 0 || sy === 0 || sz === 0) {
Matrix2.IdentityToRef(result);
} else {
Matrix2.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
}
return this;
};
Matrix2.FromArray = function(array, offset) {
var result = new Matrix2();
if (!offset) {
offset = 0;
}
Matrix2.FromArrayToRef(array, offset, result);
return result;
};
Matrix2.FromArrayToRef = function(array, offset, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = array[index + offset];
}
result._markAsUpdated();
};
Matrix2.FromFloat32ArrayToRefScaled = function(array, offset, scale, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = array[index + offset] * scale;
}
result._markAsUpdated();
};
Matrix2.FromValuesToRef = function(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
result.m[0] = initialM11;
result.m[1] = initialM12;
result.m[2] = initialM13;
result.m[3] = initialM14;
result.m[4] = initialM21;
result.m[5] = initialM22;
result.m[6] = initialM23;
result.m[7] = initialM24;
result.m[8] = initialM31;
result.m[9] = initialM32;
result.m[10] = initialM33;
result.m[11] = initialM34;
result.m[12] = initialM41;
result.m[13] = initialM42;
result.m[14] = initialM43;
result.m[15] = initialM44;
result._markAsUpdated();
};
Object.defineProperty(Matrix2, "IdentityReadOnly", {
/**
* Gets an identity matrix that must not be updated
*/
get: function() {
return Matrix2._identityReadOnly;
},
enumerable: true,
configurable: true
});
Matrix2.FromValues = function(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
var result = new Matrix2();
result.m[0] = initialM11;
result.m[1] = initialM12;
result.m[2] = initialM13;
result.m[3] = initialM14;
result.m[4] = initialM21;
result.m[5] = initialM22;
result.m[6] = initialM23;
result.m[7] = initialM24;
result.m[8] = initialM31;
result.m[9] = initialM32;
result.m[10] = initialM33;
result.m[11] = initialM34;
result.m[12] = initialM41;
result.m[13] = initialM42;
result.m[14] = initialM43;
result.m[15] = initialM44;
return result;
};
Matrix2.Compose = function(scale, rotation, translation) {
var result = Matrix2.Identity();
Matrix2.ComposeToRef(scale, rotation, translation, result);
return result;
};
Matrix2.ComposeToRef = function(scale, rotation, translation, result) {
Matrix2.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
rotation.toRotationMatrix(MathTmp.Matrix[0]);
MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
result.setTranslation(translation);
};
Matrix2.Identity = function() {
return Matrix2.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
};
Matrix2.IdentityToRef = function(result) {
Matrix2.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, result);
};
Matrix2.Zero = function() {
return Matrix2.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
};
Matrix2.RotationX = function(angle) {
var result = new Matrix2();
Matrix2.RotationXToRef(angle, result);
return result;
};
Matrix2.Invert = function(source) {
var result = new Matrix2();
source.invertToRef(result);
return result;
};
Matrix2.RotationXToRef = function(angle, result) {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[0] = 1;
result.m[15] = 1;
result.m[5] = c;
result.m[10] = c;
result.m[9] = -s;
result.m[6] = s;
result.m[1] = 0;
result.m[2] = 0;
result.m[3] = 0;
result.m[4] = 0;
result.m[7] = 0;
result.m[8] = 0;
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result._markAsUpdated();
};
Matrix2.RotationY = function(angle) {
var result = new Matrix2();
Matrix2.RotationYToRef(angle, result);
return result;
};
Matrix2.RotationYToRef = function(angle, result) {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[5] = 1;
result.m[15] = 1;
result.m[0] = c;
result.m[2] = -s;
result.m[8] = s;
result.m[10] = c;
result.m[1] = 0;
result.m[3] = 0;
result.m[4] = 0;
result.m[6] = 0;
result.m[7] = 0;
result.m[9] = 0;
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result._markAsUpdated();
};
Matrix2.RotationZ = function(angle) {
var result = new Matrix2();
Matrix2.RotationZToRef(angle, result);
return result;
};
Matrix2.RotationZToRef = function(angle, result) {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[10] = 1;
result.m[15] = 1;
result.m[0] = c;
result.m[1] = s;
result.m[4] = -s;
result.m[5] = c;
result.m[2] = 0;
result.m[3] = 0;
result.m[6] = 0;
result.m[7] = 0;
result.m[8] = 0;
result.m[9] = 0;
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result._markAsUpdated();
};
Matrix2.RotationAxis = function(axis, angle) {
var result = Matrix2.Zero();
Matrix2.RotationAxisToRef(axis, angle, result);
return result;
};
Matrix2.RotationAxisToRef = function(axis, angle, result) {
var s = Math.sin(-angle);
var c = Math.cos(-angle);
var c1 = 1 - c;
axis.normalize();
result.m[0] = axis.x * axis.x * c1 + c;
result.m[1] = axis.x * axis.y * c1 - axis.z * s;
result.m[2] = axis.x * axis.z * c1 + axis.y * s;
result.m[3] = 0;
result.m[4] = axis.y * axis.x * c1 + axis.z * s;
result.m[5] = axis.y * axis.y * c1 + c;
result.m[6] = axis.y * axis.z * c1 - axis.x * s;
result.m[7] = 0;
result.m[8] = axis.z * axis.x * c1 - axis.y * s;
result.m[9] = axis.z * axis.y * c1 + axis.x * s;
result.m[10] = axis.z * axis.z * c1 + c;
result.m[11] = 0;
result.m[15] = 1;
result._markAsUpdated();
};
Matrix2.RotationYawPitchRoll = function(yaw, pitch, roll) {
var result = new Matrix2();
Matrix2.RotationYawPitchRollToRef(yaw, pitch, roll, result);
return result;
};
Matrix2.RotationYawPitchRollToRef = function(yaw, pitch, roll, result) {
Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
this._tempQuaternion.toRotationMatrix(result);
};
Matrix2.Scaling = function(x, y, z) {
var result = Matrix2.Zero();
Matrix2.ScalingToRef(x, y, z, result);
return result;
};
Matrix2.ScalingToRef = function(x, y, z, result) {
result.m[0] = x;
result.m[1] = 0;
result.m[2] = 0;
result.m[3] = 0;
result.m[4] = 0;
result.m[5] = y;
result.m[6] = 0;
result.m[7] = 0;
result.m[8] = 0;
result.m[9] = 0;
result.m[10] = z;
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result.m[15] = 1;
result._markAsUpdated();
};
Matrix2.Translation = function(x, y, z) {
var result = Matrix2.Identity();
Matrix2.TranslationToRef(x, y, z, result);
return result;
};
Matrix2.TranslationToRef = function(x, y, z, result) {
Matrix2.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1, result);
};
Matrix2.Lerp = function(startValue, endValue, gradient) {
var result = Matrix2.Zero();
Matrix2.LerpToRef(startValue, endValue, gradient, result);
return result;
};
Matrix2.LerpToRef = function(startValue, endValue, gradient, result) {
for (var index = 0; index < 16; index++) {
result.m[index] = startValue.m[index] * (1 - gradient) + endValue.m[index] * gradient;
}
result._markAsUpdated();
};
Matrix2.DecomposeLerp = function(startValue, endValue, gradient) {
var result = Matrix2.Zero();
Matrix2.DecomposeLerpToRef(startValue, endValue, gradient, result);
return result;
};
Matrix2.DecomposeLerpToRef = function(startValue, endValue, gradient, result) {
var startScale = MathTmp.Vector3[0];
var startRotation = MathTmp.Quaternion[0];
var startTranslation = MathTmp.Vector3[1];
startValue.decompose(startScale, startRotation, startTranslation);
var endScale = MathTmp.Vector3[2];
var endRotation = MathTmp.Quaternion[1];
var endTranslation = MathTmp.Vector3[3];
endValue.decompose(endScale, endRotation, endTranslation);
var resultScale = MathTmp.Vector3[4];
Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
var resultRotation = MathTmp.Quaternion[2];
Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
var resultTranslation = MathTmp.Vector3[5];
Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
Matrix2.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
};
Matrix2.LookAtLH = function(eye, target, up) {
var result = Matrix2.Zero();
Matrix2.LookAtLHToRef(eye, target, up, result);
return result;
};
Matrix2.LookAtLHToRef = function(eye, target, up, result) {
target.subtractToRef(eye, this._zAxis);
this._zAxis.normalize();
Vector3.CrossToRef(up, this._zAxis, this._xAxis);
if (this._xAxis.lengthSquared() === 0) {
this._xAxis.x = 1;
} else {
this._xAxis.normalize();
}
Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
this._yAxis.normalize();
var ex = -Vector3.Dot(this._xAxis, eye);
var ey = -Vector3.Dot(this._yAxis, eye);
var ez = -Vector3.Dot(this._zAxis, eye);
return Matrix2.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
};
Matrix2.LookAtRH = function(eye, target, up) {
var result = Matrix2.Zero();
Matrix2.LookAtRHToRef(eye, target, up, result);
return result;
};
Matrix2.LookAtRHToRef = function(eye, target, up, result) {
eye.subtractToRef(target, this._zAxis);
this._zAxis.normalize();
Vector3.CrossToRef(up, this._zAxis, this._xAxis);
if (this._xAxis.lengthSquared() === 0) {
this._xAxis.x = 1;
} else {
this._xAxis.normalize();
}
Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
this._yAxis.normalize();
var ex = -Vector3.Dot(this._xAxis, eye);
var ey = -Vector3.Dot(this._yAxis, eye);
var ez = -Vector3.Dot(this._zAxis, eye);
return Matrix2.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
};
Matrix2.OrthoLH = function(width, height, znear, zfar) {
var matrix = Matrix2.Zero();
Matrix2.OrthoLHToRef(width, height, znear, zfar, matrix);
return matrix;
};
Matrix2.OrthoLHToRef = function(width, height, znear, zfar, result) {
var n = znear;
var f = zfar;
var a = 2 / width;
var b2 = 2 / height;
var c = 2 / (f - n);
var d = -(f + n) / (f - n);
Matrix2.FromValuesToRef(a, 0, 0, 0, 0, b2, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
};
Matrix2.OrthoOffCenterLH = function(left, right, bottom, top, znear, zfar) {
var matrix = Matrix2.Zero();
Matrix2.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
return matrix;
};
Matrix2.OrthoOffCenterLHToRef = function(left, right, bottom, top, znear, zfar, result) {
var n = znear;
var f = zfar;
var a = 2 / (right - left);
var b2 = 2 / (top - bottom);
var c = 2 / (f - n);
var d = -(f + n) / (f - n);
var i0 = (left + right) / (left - right);
var i1 = (top + bottom) / (bottom - top);
Matrix2.FromValuesToRef(a, 0, 0, 0, 0, b2, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
};
Matrix2.OrthoOffCenterRH = function(left, right, bottom, top, znear, zfar) {
var matrix = Matrix2.Zero();
Matrix2.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
return matrix;
};
Matrix2.OrthoOffCenterRHToRef = function(left, right, bottom, top, znear, zfar, result) {
Matrix2.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
result.m[10] *= -1;
};
Matrix2.PerspectiveLH = function(width, height, znear, zfar) {
var matrix = Matrix2.Zero();
var n = znear;
var f = zfar;
var a = 2 * n / width;
var b2 = 2 * n / height;
var c = (f + n) / (f - n);
var d = -2 * f * n / (f - n);
Matrix2.FromValuesToRef(a, 0, 0, 0, 0, b2, 0, 0, 0, 0, c, 1, 0, 0, d, 0, matrix);
return matrix;
};
Matrix2.PerspectiveFovLH = function(fov, aspect, znear, zfar) {
var matrix = Matrix2.Zero();
Matrix2.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
return matrix;
};
Matrix2.PerspectiveFovLHToRef = function(fov, aspect, znear, zfar, result, isVerticalFovFixed) {
if (isVerticalFovFixed === void 0) {
isVerticalFovFixed = true;
}
var n = znear;
var f = zfar;
var t = 1 / Math.tan(fov * 0.5);
var a = isVerticalFovFixed ? t / aspect : t;
var b2 = isVerticalFovFixed ? t : t * aspect;
var c = (f + n) / (f - n);
var d = -2 * f * n / (f - n);
Matrix2.FromValuesToRef(a, 0, 0, 0, 0, b2, 0, 0, 0, 0, c, 1, 0, 0, d, 0, result);
};
Matrix2.PerspectiveFovRH = function(fov, aspect, znear, zfar) {
var matrix = Matrix2.Zero();
Matrix2.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
return matrix;
};
Matrix2.PerspectiveFovRHToRef = function(fov, aspect, znear, zfar, result, isVerticalFovFixed) {
if (isVerticalFovFixed === void 0) {
isVerticalFovFixed = true;
}
var n = znear;
var f = zfar;
var t = 1 / Math.tan(fov * 0.5);
var a = isVerticalFovFixed ? t / aspect : t;
var b2 = isVerticalFovFixed ? t : t * aspect;
var c = -(f + n) / (f - n);
var d = -2 * f * n / (f - n);
Matrix2.FromValuesToRef(a, 0, 0, 0, 0, b2, 0, 0, 0, 0, c, -1, 0, 0, d, 0, result);
};
Matrix2.PerspectiveFovWebVRToRef = function(fov, znear, zfar, result, rightHanded) {
if (rightHanded === void 0) {
rightHanded = false;
}
var rightHandedFactor = rightHanded ? -1 : 1;
var upTan = Math.tan(fov.upDegrees * Math.PI / 180);
var downTan = Math.tan(fov.downDegrees * Math.PI / 180);
var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180);
var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180);
var xScale = 2 / (leftTan + rightTan);
var yScale = 2 / (upTan + downTan);
result.m[0] = xScale;
result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0;
result.m[5] = yScale;
result.m[6] = result.m[7] = 0;
result.m[8] = (leftTan - rightTan) * xScale * 0.5;
result.m[9] = -((upTan - downTan) * yScale * 0.5);
result.m[10] = -zfar / (znear - zfar);
result.m[11] = 1 * rightHandedFactor;
result.m[12] = result.m[13] = result.m[15] = 0;
result.m[14] = -(2 * zfar * znear) / (zfar - znear);
result._markAsUpdated();
};
Matrix2.GetFinalMatrix = function(viewport, world, view, projection, zmin, zmax) {
var cw = viewport.width;
var ch = viewport.height;
var cx = viewport.x;
var cy = viewport.y;
var viewportMatrix = Matrix2.FromValues(cw / 2, 0, 0, 0, 0, -ch / 2, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2, ch / 2 + cy, zmin, 1);
return world.multiply(view).multiply(projection).multiply(viewportMatrix);
};
Matrix2.GetAsMatrix2x2 = function(matrix) {
return new Float32Array([
matrix.m[0],
matrix.m[1],
matrix.m[4],
matrix.m[5]
]);
};
Matrix2.GetAsMatrix3x3 = function(matrix) {
return new Float32Array([
matrix.m[0],
matrix.m[1],
matrix.m[2],
matrix.m[4],
matrix.m[5],
matrix.m[6],
matrix.m[8],
matrix.m[9],
matrix.m[10]
]);
};
Matrix2.Transpose = function(matrix) {
var result = new Matrix2();
Matrix2.TransposeToRef(matrix, result);
return result;
};
Matrix2.TransposeToRef = function(matrix, result) {
result.m[0] = matrix.m[0];
result.m[1] = matrix.m[4];
result.m[2] = matrix.m[8];
result.m[3] = matrix.m[12];
result.m[4] = matrix.m[1];
result.m[5] = matrix.m[5];
result.m[6] = matrix.m[9];
result.m[7] = matrix.m[13];
result.m[8] = matrix.m[2];
result.m[9] = matrix.m[6];
result.m[10] = matrix.m[10];
result.m[11] = matrix.m[14];
result.m[12] = matrix.m[3];
result.m[13] = matrix.m[7];
result.m[14] = matrix.m[11];
result.m[15] = matrix.m[15];
};
Matrix2.Reflection = function(plane) {
var matrix = new Matrix2();
Matrix2.ReflectionToRef(plane, matrix);
return matrix;
};
Matrix2.ReflectionToRef = function(plane, result) {
plane.normalize();
var x = plane.normal.x;
var y = plane.normal.y;
var z = plane.normal.z;
var temp = -2 * x;
var temp2 = -2 * y;
var temp3 = -2 * z;
result.m[0] = temp * x + 1;
result.m[1] = temp2 * x;
result.m[2] = temp3 * x;
result.m[3] = 0;
result.m[4] = temp * y;
result.m[5] = temp2 * y + 1;
result.m[6] = temp3 * y;
result.m[7] = 0;
result.m[8] = temp * z;
result.m[9] = temp2 * z;
result.m[10] = temp3 * z + 1;
result.m[11] = 0;
result.m[12] = temp * plane.d;
result.m[13] = temp2 * plane.d;
result.m[14] = temp3 * plane.d;
result.m[15] = 1;
result._markAsUpdated();
};
Matrix2.FromXYZAxesToRef = function(xaxis, yaxis, zaxis, result) {
result.m[0] = xaxis.x;
result.m[1] = xaxis.y;
result.m[2] = xaxis.z;
result.m[3] = 0;
result.m[4] = yaxis.x;
result.m[5] = yaxis.y;
result.m[6] = yaxis.z;
result.m[7] = 0;
result.m[8] = zaxis.x;
result.m[9] = zaxis.y;
result.m[10] = zaxis.z;
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result.m[15] = 1;
result._markAsUpdated();
};
Matrix2.FromQuaternionToRef = function(quat, result) {
var xx = quat.x * quat.x;
var yy = quat.y * quat.y;
var zz = quat.z * quat.z;
var xy = quat.x * quat.y;
var zw = quat.z * quat.w;
var zx = quat.z * quat.x;
var yw = quat.y * quat.w;
var yz = quat.y * quat.z;
var xw = quat.x * quat.w;
result.m[0] = 1 - 2 * (yy + zz);
result.m[1] = 2 * (xy + zw);
result.m[2] = 2 * (zx - yw);
result.m[3] = 0;
result.m[4] = 2 * (xy - zw);
result.m[5] = 1 - 2 * (zz + xx);
result.m[6] = 2 * (yz + xw);
result.m[7] = 0;
result.m[8] = 2 * (zx + yw);
result.m[9] = 2 * (yz - xw);
result.m[10] = 1 - 2 * (yy + xx);
result.m[11] = 0;
result.m[12] = 0;
result.m[13] = 0;
result.m[14] = 0;
result.m[15] = 1;
result._markAsUpdated();
};
Matrix2._tempQuaternion = new Quaternion();
Matrix2._xAxis = Vector3.Zero();
Matrix2._yAxis = Vector3.Zero();
Matrix2._zAxis = Vector3.Zero();
Matrix2._updateFlagSeed = 0;
Matrix2._identityReadOnly = Matrix2.Identity();
return Matrix2;
}()
);
BABYLON2.Matrix = Matrix;
var Plane = (
/** @class */
function() {
function Plane2(a, b2, c, d) {
this.normal = new Vector3(a, b2, c);
this.d = d;
}
Plane2.prototype.asArray = function() {
return [this.normal.x, this.normal.y, this.normal.z, this.d];
};
Plane2.prototype.clone = function() {
return new Plane2(this.normal.x, this.normal.y, this.normal.z, this.d);
};
Plane2.prototype.getClassName = function() {
return "Plane";
};
Plane2.prototype.getHashCode = function() {
var hash = this.normal.getHashCode();
hash = hash * 397 ^ (this.d || 0);
return hash;
};
Plane2.prototype.normalize = function() {
var norm = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z);
var magnitude = 0;
if (norm !== 0) {
magnitude = 1 / norm;
}
this.normal.x *= magnitude;
this.normal.y *= magnitude;
this.normal.z *= magnitude;
this.d *= magnitude;
return this;
};
Plane2.prototype.transform = function(transformation) {
var transposedMatrix = Matrix.Transpose(transformation);
var x = this.normal.x;
var y = this.normal.y;
var z = this.normal.z;
var d = this.d;
var normalX = x * transposedMatrix.m[0] + y * transposedMatrix.m[1] + z * transposedMatrix.m[2] + d * transposedMatrix.m[3];
var normalY = x * transposedMatrix.m[4] + y * transposedMatrix.m[5] + z * transposedMatrix.m[6] + d * transposedMatrix.m[7];
var normalZ = x * transposedMatrix.m[8] + y * transposedMatrix.m[9] + z * transposedMatrix.m[10] + d * transposedMatrix.m[11];
var finalD = x * transposedMatrix.m[12] + y * transposedMatrix.m[13] + z * transposedMatrix.m[14] + d * transposedMatrix.m[15];
return new Plane2(normalX, normalY, normalZ, finalD);
};
Plane2.prototype.dotCoordinate = function(point) {
return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d;
};
Plane2.prototype.copyFromPoints = function(point1, point2, point3) {
var x1 = point2.x - point1.x;
var y1 = point2.y - point1.y;
var z1 = point2.z - point1.z;
var x2 = point3.x - point1.x;
var y2 = point3.y - point1.y;
var z2 = point3.z - point1.z;
var yz = y1 * z2 - z1 * y2;
var xz = z1 * x2 - x1 * z2;
var xy = x1 * y2 - y1 * x2;
var pyth = Math.sqrt(yz * yz + xz * xz + xy * xy);
var invPyth;
if (pyth !== 0) {
invPyth = 1 / pyth;
} else {
invPyth = 0;
}
this.normal.x = yz * invPyth;
this.normal.y = xz * invPyth;
this.normal.z = xy * invPyth;
this.d = -(this.normal.x * point1.x + this.normal.y * point1.y + this.normal.z * point1.z);
return this;
};
Plane2.prototype.isFrontFacingTo = function(direction, epsilon) {
var dot = Vector3.Dot(this.normal, direction);
return dot <= epsilon;
};
Plane2.prototype.signedDistanceTo = function(point) {
return Vector3.Dot(point, this.normal) + this.d;
};
Plane2.FromArray = function(array) {
return new Plane2(array[0], array[1], array[2], array[3]);
};
Plane2.FromPoints = function(point1, point2, point3) {
var result = new Plane2(0, 0, 0, 0);
result.copyFromPoints(point1, point2, point3);
return result;
};
Plane2.FromPositionAndNormal = function(origin, normal) {
var result = new Plane2(0, 0, 0, 0);
normal.normalize();
result.normal = normal;
result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
return result;
};
Plane2.SignedDistanceToPlaneFromPositionAndNormal = function(origin, normal, point) {
var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
return Vector3.Dot(point, normal) + d;
};
return Plane2;
}()
);
BABYLON2.Plane = Plane;
var Viewport = (
/** @class */
function() {
function Viewport2(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Viewport2.prototype.toGlobal = function(renderWidthOrEngine, renderHeight) {
if (renderWidthOrEngine.getRenderWidth) {
var engine = renderWidthOrEngine;
return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
}
var renderWidth = renderWidthOrEngine;
return new Viewport2(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
};
Viewport2.prototype.clone = function() {
return new Viewport2(this.x, this.y, this.width, this.height);
};
return Viewport2;
}()
);
BABYLON2.Viewport = Viewport;
var Frustum = (
/** @class */
function() {
function Frustum2() {
}
Frustum2.GetPlanes = function(transform) {
var frustumPlanes = [];
for (var index = 0; index < 6; index++) {
frustumPlanes.push(new Plane(0, 0, 0, 0));
}
Frustum2.GetPlanesToRef(transform, frustumPlanes);
return frustumPlanes;
};
Frustum2.GetNearPlaneToRef = function(transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] + transform.m[2];
frustumPlane.normal.y = transform.m[7] + transform.m[6];
frustumPlane.normal.z = transform.m[11] + transform.m[10];
frustumPlane.d = transform.m[15] + transform.m[14];
frustumPlane.normalize();
};
Frustum2.GetFarPlaneToRef = function(transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] - transform.m[2];
frustumPlane.normal.y = transform.m[7] - transform.m[6];
frustumPlane.normal.z = transform.m[11] - transform.m[10];
frustumPlane.d = transform.m[15] - transform.m[14];
frustumPlane.normalize();
};
Frustum2.GetLeftPlaneToRef = function(transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] + transform.m[0];
frustumPlane.normal.y = transform.m[7] + transform.m[4];
frustumPlane.normal.z = transform.m[11] + transform.m[8];
frustumPlane.d = transform.m[15] + transform.m[12];
frustumPlane.normalize();
};
Frustum2.GetRightPlaneToRef = function(transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] - transform.m[0];
frustumPlane.normal.y = transform.m[7] - transform.m[4];
frustumPlane.normal.z = transform.m[11] - transform.m[8];
frustumPlane.d = transform.m[15] - transform.m[12];
frustumPlane.normalize();
};
Frustum2.GetTopPlaneToRef = function(transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] - transform.m[1];
frustumPlane.normal.y = transform.m[7] - transform.m[5];
frustumPlane.normal.z = transform.m[11] - transform.m[9];
frustumPlane.d = transform.m[15] - transform.m[13];
frustumPlane.normalize();
};
Frustum2.GetBottomPlaneToRef = function(transform, frustumPlane) {
frustumPlane.normal.x = transform.m[3] + transform.m[1];
frustumPlane.normal.y = transform.m[7] + transform.m[5];
frustumPlane.normal.z = transform.m[11] + transform.m[9];
frustumPlane.d = transform.m[15] + transform.m[13];
frustumPlane.normalize();
};
Frustum2.GetPlanesToRef = function(transform, frustumPlanes) {
Frustum2.GetNearPlaneToRef(transform, frustumPlanes[0]);
Frustum2.GetFarPlaneToRef(transform, frustumPlanes[1]);
Frustum2.GetLeftPlaneToRef(transform, frustumPlanes[2]);
Frustum2.GetRightPlaneToRef(transform, frustumPlanes[3]);
Frustum2.GetTopPlaneToRef(transform, frustumPlanes[4]);
Frustum2.GetBottomPlaneToRef(transform, frustumPlanes[5]);
};
return Frustum2;
}()
);
BABYLON2.Frustum = Frustum;
var Space;
(function(Space2) {
Space2[Space2["LOCAL"] = 0] = "LOCAL";
Space2[Space2["WORLD"] = 1] = "WORLD";
Space2[Space2["BONE"] = 2] = "BONE";
})(Space = BABYLON2.Space || (BABYLON2.Space = {}));
var Axis = (
/** @class */
function() {
function Axis2() {
}
Axis2.X = new Vector3(1, 0, 0);
Axis2.Y = new Vector3(0, 1, 0);
Axis2.Z = new Vector3(0, 0, 1);
return Axis2;
}()
);
BABYLON2.Axis = Axis;
var BezierCurve = (
/** @class */
function() {
function BezierCurve2() {
}
BezierCurve2.Interpolate = function(t, x1, y1, x2, y2) {
var f0 = 1 - 3 * x2 + 3 * x1;
var f1 = 3 * x2 - 6 * x1;
var f2 = 3 * x1;
var refinedT = t;
for (var i2 = 0; i2 < 5; i2++) {
var refinedT2 = refinedT * refinedT;
var refinedT3 = refinedT2 * refinedT;
var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
var slope = 1 / (3 * f0 * refinedT2 + 2 * f1 * refinedT + f2);
refinedT -= (x - t) * slope;
refinedT = Math.min(1, Math.max(0, refinedT));
}
return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
};
return BezierCurve2;
}()
);
BABYLON2.BezierCurve = BezierCurve;
var Orientation;
(function(Orientation2) {
Orientation2[Orientation2["CW"] = 0] = "CW";
Orientation2[Orientation2["CCW"] = 1] = "CCW";
})(Orientation = BABYLON2.Orientation || (BABYLON2.Orientation = {}));
var Angle = (
/** @class */
function() {
function Angle2(radians) {
this._radians = radians;
if (this._radians < 0) {
this._radians += 2 * Math.PI;
}
}
Angle2.prototype.degrees = function() {
return this._radians * 180 / Math.PI;
};
Angle2.prototype.radians = function() {
return this._radians;
};
Angle2.BetweenTwoPoints = function(a, b2) {
var delta = b2.subtract(a);
var theta = Math.atan2(delta.y, delta.x);
return new Angle2(theta);
};
Angle2.FromRadians = function(radians) {
return new Angle2(radians);
};
Angle2.FromDegrees = function(degrees) {
return new Angle2(degrees * Math.PI / 180);
};
return Angle2;
}()
);
BABYLON2.Angle = Angle;
var Arc2 = (
/** @class */
function() {
function Arc22(startPoint, midPoint, endPoint) {
this.startPoint = startPoint;
this.midPoint = midPoint;
this.endPoint = endPoint;
var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2;
var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2;
var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
this.radius = this.centerPoint.subtract(this.startPoint).length();
this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
var a1 = this.startAngle.degrees();
var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
if (a2 - a1 > 180) {
a2 -= 360;
}
if (a2 - a1 < -180) {
a2 += 360;
}
if (a3 - a2 > 180) {
a3 -= 360;
}
if (a3 - a2 < -180) {
a3 += 360;
}
this.orientation = a2 - a1 < 0 ? Orientation.CW : Orientation.CCW;
this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
}
return Arc22;
}()
);
BABYLON2.Arc2 = Arc2;
var Path2 = (
/** @class */
function() {
function Path22(x, y) {
this._points = new Array();
this._length = 0;
this.closed = false;
this._points.push(new Vector2(x, y));
}
Path22.prototype.addLineTo = function(x, y) {
if (this.closed) {
return this;
}
var newPoint = new Vector2(x, y);
var previousPoint = this._points[this._points.length - 1];
this._points.push(newPoint);
this._length += newPoint.subtract(previousPoint).length();
return this;
};
Path22.prototype.addArcTo = function(midX, midY, endX, endY, numberOfSegments) {
if (numberOfSegments === void 0) {
numberOfSegments = 36;
}
if (this.closed) {
return this;
}
var startPoint = this._points[this._points.length - 1];
var midPoint = new Vector2(midX, midY);
var endPoint = new Vector2(endX, endY);
var arc = new Arc2(startPoint, midPoint, endPoint);
var increment = arc.angle.radians() / numberOfSegments;
if (arc.orientation === Orientation.CW) {
increment *= -1;
}
var currentAngle = arc.startAngle.radians() + increment;
for (var i2 = 0; i2 < numberOfSegments; i2++) {
var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
this.addLineTo(x, y);
currentAngle += increment;
}
return this;
};
Path22.prototype.close = function() {
this.closed = true;
return this;
};
Path22.prototype.length = function() {
var result = this._length;
if (!this.closed) {
var lastPoint = this._points[this._points.length - 1];
var firstPoint = this._points[0];
result += firstPoint.subtract(lastPoint).length();
}
return result;
};
Path22.prototype.getPoints = function() {
return this._points;
};
Path22.prototype.getPointAtLengthPosition = function(normalizedLengthPosition) {
if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
return Vector2.Zero();
}
var lengthPosition = normalizedLengthPosition * this.length();
var previousOffset = 0;
for (var i2 = 0; i2 < this._points.length; i2++) {
var j = (i2 + 1) % this._points.length;
var a = this._points[i2];
var b2 = this._points[j];
var bToA = b2.subtract(a);
var nextOffset = bToA.length() + previousOffset;
if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
var dir = bToA.normalize();
var localOffset = lengthPosition - previousOffset;
return new Vector2(a.x + dir.x * localOffset, a.y + dir.y * localOffset);
}
previousOffset = nextOffset;
}
return Vector2.Zero();
};
Path22.StartingAt = function(x, y) {
return new Path22(x, y);
};
return Path22;
}()
);
BABYLON2.Path2 = Path2;
var Path3D = (
/** @class */
function() {
function Path3D2(path, firstNormal, raw) {
if (firstNormal === void 0) {
firstNormal = null;
}
this.path = path;
this._curve = new Array();
this._distances = new Array();
this._tangents = new Array();
this._normals = new Array();
this._binormals = new Array();
for (var p = 0; p < path.length; p++) {
this._curve[p] = path[p].clone();
}
this._raw = raw || false;
this._compute(firstNormal);
}
Path3D2.prototype.getCurve = function() {
return this._curve;
};
Path3D2.prototype.getTangents = function() {
return this._tangents;
};
Path3D2.prototype.getNormals = function() {
return this._normals;
};
Path3D2.prototype.getBinormals = function() {
return this._binormals;
};
Path3D2.prototype.getDistances = function() {
return this._distances;
};
Path3D2.prototype.update = function(path, firstNormal) {
if (firstNormal === void 0) {
firstNormal = null;
}
for (var p = 0; p < path.length; p++) {
this._curve[p].x = path[p].x;
this._curve[p].y = path[p].y;
this._curve[p].z = path[p].z;
}
this._compute(firstNormal);
return this;
};
Path3D2.prototype._compute = function(firstNormal) {
var l = this._curve.length;
this._tangents[0] = this._getFirstNonNullVector(0);
if (!this._raw) {
this._tangents[0].normalize();
}
this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
if (!this._raw) {
this._tangents[l - 1].normalize();
}
var tg0 = this._tangents[0];
var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
this._normals[0] = pp0;
if (!this._raw) {
this._normals[0].normalize();
}
this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
if (!this._raw) {
this._binormals[0].normalize();
}
this._distances[0] = 0;
var prev;
var cur;
var curTang;
var prevBinor;
for (var i2 = 1; i2 < l; i2++) {
prev = this._getLastNonNullVector(i2);
if (i2 < l - 1) {
cur = this._getFirstNonNullVector(i2);
this._tangents[i2] = prev.add(cur);
this._tangents[i2].normalize();
}
this._distances[i2] = this._distances[i2 - 1] + prev.length();
curTang = this._tangents[i2];
prevBinor = this._binormals[i2 - 1];
this._normals[i2] = Vector3.Cross(prevBinor, curTang);
if (!this._raw) {
this._normals[i2].normalize();
}
this._binormals[i2] = Vector3.Cross(curTang, this._normals[i2]);
if (!this._raw) {
this._binormals[i2].normalize();
}
}
};
Path3D2.prototype._getFirstNonNullVector = function(index) {
var i2 = 1;
var nNVector = this._curve[index + i2].subtract(this._curve[index]);
while (nNVector.length() === 0 && index + i2 + 1 < this._curve.length) {
i2++;
nNVector = this._curve[index + i2].subtract(this._curve[index]);
}
return nNVector;
};
Path3D2.prototype._getLastNonNullVector = function(index) {
var i2 = 1;
var nLVector = this._curve[index].subtract(this._curve[index - i2]);
while (nLVector.length() === 0 && index > i2 + 1) {
i2++;
nLVector = this._curve[index].subtract(this._curve[index - i2]);
}
return nLVector;
};
Path3D2.prototype._normalVector = function(v0, vt, va) {
var normal0;
var tgl = vt.length();
if (tgl === 0) {
tgl = 1;
}
if (va === void 0 || va === null) {
var point;
if (!BABYLON2.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1, BABYLON2.Epsilon)) {
point = new Vector3(0, -1, 0);
} else if (!BABYLON2.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1, BABYLON2.Epsilon)) {
point = new Vector3(1, 0, 0);
} else if (!BABYLON2.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1, BABYLON2.Epsilon)) {
point = new Vector3(0, 0, 1);
} else {
point = Vector3.Zero();
}
normal0 = Vector3.Cross(vt, point);
} else {
normal0 = Vector3.Cross(vt, va);
Vector3.CrossToRef(normal0, vt, normal0);
}
normal0.normalize();
return normal0;
};
return Path3D2;
}()
);
BABYLON2.Path3D = Path3D;
var Curve3 = (
/** @class */
function() {
function Curve32(points) {
this._length = 0;
this._points = points;
this._length = this._computeLength(points);
}
Curve32.CreateQuadraticBezier = function(v0, v1, v2, nbPoints) {
nbPoints = nbPoints > 2 ? nbPoints : 3;
var bez = new Array();
var equation = function(t, val0, val1, val2) {
var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
return res;
};
for (var i2 = 0; i2 <= nbPoints; i2++) {
bez.push(new Vector3(equation(i2 / nbPoints, v0.x, v1.x, v2.x), equation(i2 / nbPoints, v0.y, v1.y, v2.y), equation(i2 / nbPoints, v0.z, v1.z, v2.z)));
}
return new Curve32(bez);
};
Curve32.CreateCubicBezier = function(v0, v1, v2, v3, nbPoints) {
nbPoints = nbPoints > 3 ? nbPoints : 4;
var bez = new Array();
var equation = function(t, val0, val1, val2, val3) {
var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
return res;
};
for (var i2 = 0; i2 <= nbPoints; i2++) {
bez.push(new Vector3(equation(i2 / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i2 / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i2 / nbPoints, v0.z, v1.z, v2.z, v3.z)));
}
return new Curve32(bez);
};
Curve32.CreateHermiteSpline = function(p1, t1, p2, t2, nbPoints) {
var hermite = new Array();
var step = 1 / nbPoints;
for (var i2 = 0; i2 <= nbPoints; i2++) {
hermite.push(Vector3.Hermite(p1, t1, p2, t2, i2 * step));
}
return new Curve32(hermite);
};
Curve32.CreateCatmullRomSpline = function(points, nbPoints, closed) {
var catmullRom = new Array();
var step = 1 / nbPoints;
var amount = 0;
if (closed) {
var pointsCount = points.length;
for (var i2 = 0; i2 < pointsCount; i2++) {
amount = 0;
for (var c = 0; c < nbPoints; c++) {
catmullRom.push(Vector3.CatmullRom(points[i2 % pointsCount], points[(i2 + 1) % pointsCount], points[(i2 + 2) % pointsCount], points[(i2 + 3) % pointsCount], amount));
amount += step;
}
}
catmullRom.push(catmullRom[0]);
} else {
var totalPoints = new Array();
totalPoints.push(points[0].clone());
Array.prototype.push.apply(totalPoints, points);
totalPoints.push(points[points.length - 1].clone());
for (var i2 = 0; i2 < totalPoints.length - 3; i2++) {
amount = 0;
for (var c = 0; c < nbPoints; c++) {
catmullRom.push(Vector3.CatmullRom(totalPoints[i2], totalPoints[i2 + 1], totalPoints[i2 + 2], totalPoints[i2 + 3], amount));
amount += step;
}
}
i2--;
catmullRom.push(Vector3.CatmullRom(totalPoints[i2], totalPoints[i2 + 1], totalPoints[i2 + 2], totalPoints[i2 + 3], amount));
}
return new Curve32(catmullRom);
};
Curve32.prototype.getPoints = function() {
return this._points;
};
Curve32.prototype.length = function() {
return this._length;
};
Curve32.prototype.continue = function(curve) {
var lastPoint = this._points[this._points.length - 1];
var continuedPoints = this._points.slice();
var curvePoints = curve.getPoints();
for (var i2 = 1; i2 < curvePoints.length; i2++) {
continuedPoints.push(curvePoints[i2].subtract(curvePoints[0]).add(lastPoint));
}
var continuedCurve = new Curve32(continuedPoints);
return continuedCurve;
};
Curve32.prototype._computeLength = function(path) {
var l = 0;
for (var i2 = 1; i2 < path.length; i2++) {
l += path[i2].subtract(path[i2 - 1]).length();
}
return l;
};
return Curve32;
}()
);
BABYLON2.Curve3 = Curve3;
var PositionNormalVertex = (
/** @class */
function() {
function PositionNormalVertex2(position, normal) {
if (position === void 0) {
position = Vector3.Zero();
}
if (normal === void 0) {
normal = Vector3.Up();
}
this.position = position;
this.normal = normal;
}
PositionNormalVertex2.prototype.clone = function() {
return new PositionNormalVertex2(this.position.clone(), this.normal.clone());
};
return PositionNormalVertex2;
}()
);
BABYLON2.PositionNormalVertex = PositionNormalVertex;
var PositionNormalTextureVertex = (
/** @class */
function() {
function PositionNormalTextureVertex2(position, normal, uv) {
if (position === void 0) {
position = Vector3.Zero();
}
if (normal === void 0) {
normal = Vector3.Up();
}
if (uv === void 0) {
uv = Vector2.Zero();
}
this.position = position;
this.normal = normal;
this.uv = uv;
}
PositionNormalTextureVertex2.prototype.clone = function() {
return new PositionNormalTextureVertex2(this.position.clone(), this.normal.clone(), this.uv.clone());
};
return PositionNormalTextureVertex2;
}()
);
BABYLON2.PositionNormalTextureVertex = PositionNormalTextureVertex;
var Tmp = (
/** @class */
function() {
function Tmp2() {
}
Tmp2.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
Tmp2.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
Tmp2.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()];
Tmp2.Vector3 = [
Vector3.Zero(),
Vector3.Zero(),
Vector3.Zero(),
Vector3.Zero(),
Vector3.Zero(),
Vector3.Zero(),
Vector3.Zero(),
Vector3.Zero(),
Vector3.Zero()
];
Tmp2.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()];
Tmp2.Quaternion = [Quaternion.Zero(), Quaternion.Zero()];
Tmp2.Matrix = [
Matrix.Zero(),
Matrix.Zero(),
Matrix.Zero(),
Matrix.Zero(),
Matrix.Zero(),
Matrix.Zero(),
Matrix.Zero(),
Matrix.Zero()
];
return Tmp2;
}()
);
BABYLON2.Tmp = Tmp;
var MathTmp = (
/** @class */
function() {
function MathTmp2() {
}
MathTmp2.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
MathTmp2.Matrix = [Matrix.Zero(), Matrix.Zero()];
MathTmp2.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
return MathTmp2;
}()
);
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Scalar = (
/** @class */
function() {
function Scalar2() {
}
Scalar2.WithinEpsilon = function(a, b2, epsilon) {
if (epsilon === void 0) {
epsilon = 1401298e-51;
}
var num = a - b2;
return -epsilon <= num && num <= epsilon;
};
Scalar2.ToHex = function(i2) {
var str = i2.toString(16);
if (i2 <= 15) {
return ("0" + str).toUpperCase();
}
return str.toUpperCase();
};
Scalar2.Sign = function(value) {
value = +value;
if (value === 0 || isNaN(value)) {
return value;
}
return value > 0 ? 1 : -1;
};
Scalar2.Clamp = function(value, min, max) {
if (min === void 0) {
min = 0;
}
if (max === void 0) {
max = 1;
}
return Math.min(max, Math.max(min, value));
};
Scalar2.Log2 = function(value) {
return Math.log(value) * Math.LOG2E;
};
Scalar2.Repeat = function(value, length) {
return value - Math.floor(value / length) * length;
};
Scalar2.Normalize = function(value, min, max) {
return (value - min) / (max - min);
};
Scalar2.Denormalize = function(normalized, min, max) {
return normalized * (max - min) + min;
};
Scalar2.DeltaAngle = function(current, target) {
var num = Scalar2.Repeat(target - current, 360);
if (num > 180) {
num -= 360;
}
return num;
};
Scalar2.PingPong = function(tx, length) {
var t = Scalar2.Repeat(tx, length * 2);
return length - Math.abs(t - length);
};
Scalar2.SmoothStep = function(from, to, tx) {
var t = Scalar2.Clamp(tx);
t = -2 * t * t * t + 3 * t * t;
return to * t + from * (1 - t);
};
Scalar2.MoveTowards = function(current, target, maxDelta) {
var result = 0;
if (Math.abs(target - current) <= maxDelta) {
result = target;
} else {
result = current + Scalar2.Sign(target - current) * maxDelta;
}
return result;
};
Scalar2.MoveTowardsAngle = function(current, target, maxDelta) {
var num = Scalar2.DeltaAngle(current, target);
var result = 0;
if (-maxDelta < num && num < maxDelta) {
result = target;
} else {
target = current + num;
result = Scalar2.MoveTowards(current, target, maxDelta);
}
return result;
};
Scalar2.Lerp = function(start, end, amount) {
return start + (end - start) * amount;
};
Scalar2.LerpAngle = function(start, end, amount) {
var num = Scalar2.Repeat(end - start, 360);
if (num > 180) {
num -= 360;
}
return start + num * Scalar2.Clamp(amount);
};
Scalar2.InverseLerp = function(a, b2, value) {
var result = 0;
if (a != b2) {
result = Scalar2.Clamp((value - a) / (b2 - a));
} else {
result = 0;
}
return result;
};
Scalar2.Hermite = function(value1, tangent1, value2, tangent2, amount) {
var squared = amount * amount;
var cubed = amount * squared;
var part1 = 2 * cubed - 3 * squared + 1;
var part2 = -2 * cubed + 3 * squared;
var part3 = cubed - 2 * squared + amount;
var part4 = cubed - squared;
return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4;
};
Scalar2.RandomRange = function(min, max) {
if (min === max) {
return min;
}
return Math.random() * (max - min) + min;
};
Scalar2.RangeToPercent = function(number, min, max) {
return (number - min) / (max - min);
};
Scalar2.PercentToRange = function(percent, min, max) {
return (max - min) * percent + min;
};
Scalar2.NormalizeRadians = function(angle) {
angle -= Scalar2.TwoPi * Math.floor((angle + Math.PI) / Scalar2.TwoPi);
return angle;
};
Scalar2.TwoPi = Math.PI * 2;
return Scalar2;
}()
);
BABYLON2.Scalar = Scalar;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var __decoratorInitialStore = {};
var __mergedStore = {};
var _copySource = function(creationFunction, source, instanciate) {
var destination = creationFunction();
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(destination, source.tags);
}
var classStore = getMergedStore(destination);
for (var property in classStore) {
var propertyDescriptor = classStore[property];
var sourceProperty = source[property];
var propertyType = propertyDescriptor.type;
if (sourceProperty !== void 0 && sourceProperty !== null) {
switch (propertyType) {
case 0:
case 6:
case 11:
destination[property] = sourceProperty;
break;
case 1:
destination[property] = instanciate || sourceProperty.isRenderTarget ? sourceProperty : sourceProperty.clone();
break;
case 2:
case 3:
case 4:
case 5:
case 7:
case 10:
destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
break;
}
}
}
return destination;
};
function getDirectStore(target) {
var classKey = target.getClassName();
if (!__decoratorInitialStore[classKey]) {
__decoratorInitialStore[classKey] = {};
}
return __decoratorInitialStore[classKey];
}
function getMergedStore(target) {
var classKey = target.getClassName();
if (__mergedStore[classKey]) {
return __mergedStore[classKey];
}
__mergedStore[classKey] = {};
var store = __mergedStore[classKey];
var currentTarget = target;
var currentKey = classKey;
while (currentKey) {
var initialStore = __decoratorInitialStore[currentKey];
for (var property in initialStore) {
store[property] = initialStore[property];
}
var parent_1 = void 0;
var done = false;
do {
parent_1 = Object.getPrototypeOf(currentTarget);
if (!parent_1.getClassName) {
done = true;
break;
}
if (parent_1.getClassName() !== currentKey) {
break;
}
currentTarget = parent_1;
} while (parent_1);
if (done) {
break;
}
currentKey = parent_1.getClassName();
currentTarget = parent_1;
}
return store;
}
function generateSerializableMember(type, sourceName) {
return function(target, propertyKey) {
var classStore = getDirectStore(target);
if (!classStore[propertyKey]) {
classStore[propertyKey] = { type, sourceName };
}
};
}
function generateExpandMember(setCallback, targetKey) {
if (targetKey === void 0) {
targetKey = null;
}
return function(target, propertyKey) {
var key = targetKey || "_" + propertyKey;
Object.defineProperty(target, propertyKey, {
get: function() {
return this[key];
},
set: function(value) {
if (this[key] === value) {
return;
}
this[key] = value;
target[setCallback].apply(this);
},
enumerable: true,
configurable: true
});
};
}
function expandToProperty(callback, targetKey) {
if (targetKey === void 0) {
targetKey = null;
}
return generateExpandMember(callback, targetKey);
}
BABYLON2.expandToProperty = expandToProperty;
function serialize(sourceName) {
return generateSerializableMember(0, sourceName);
}
BABYLON2.serialize = serialize;
function serializeAsTexture(sourceName) {
return generateSerializableMember(1, sourceName);
}
BABYLON2.serializeAsTexture = serializeAsTexture;
function serializeAsColor3(sourceName) {
return generateSerializableMember(2, sourceName);
}
BABYLON2.serializeAsColor3 = serializeAsColor3;
function serializeAsFresnelParameters(sourceName) {
return generateSerializableMember(3, sourceName);
}
BABYLON2.serializeAsFresnelParameters = serializeAsFresnelParameters;
function serializeAsVector2(sourceName) {
return generateSerializableMember(4, sourceName);
}
BABYLON2.serializeAsVector2 = serializeAsVector2;
function serializeAsVector3(sourceName) {
return generateSerializableMember(5, sourceName);
}
BABYLON2.serializeAsVector3 = serializeAsVector3;
function serializeAsMeshReference(sourceName) {
return generateSerializableMember(6, sourceName);
}
BABYLON2.serializeAsMeshReference = serializeAsMeshReference;
function serializeAsColorCurves(sourceName) {
return generateSerializableMember(7, sourceName);
}
BABYLON2.serializeAsColorCurves = serializeAsColorCurves;
function serializeAsColor4(sourceName) {
return generateSerializableMember(8, sourceName);
}
BABYLON2.serializeAsColor4 = serializeAsColor4;
function serializeAsImageProcessingConfiguration(sourceName) {
return generateSerializableMember(9, sourceName);
}
BABYLON2.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
function serializeAsQuaternion(sourceName) {
return generateSerializableMember(10, sourceName);
}
BABYLON2.serializeAsQuaternion = serializeAsQuaternion;
function serializeAsCameraReference(sourceName) {
return generateSerializableMember(11, sourceName);
}
BABYLON2.serializeAsCameraReference = serializeAsCameraReference;
var SerializationHelper = (
/** @class */
function() {
function SerializationHelper2() {
}
SerializationHelper2.Serialize = function(entity, serializationObject) {
if (!serializationObject) {
serializationObject = {};
}
if (BABYLON2.Tags) {
serializationObject.tags = BABYLON2.Tags.GetTags(entity);
}
var serializedProperties = getMergedStore(entity);
for (var property in serializedProperties) {
var propertyDescriptor = serializedProperties[property];
var targetPropertyName = propertyDescriptor.sourceName || property;
var propertyType = propertyDescriptor.type;
var sourceProperty = entity[property];
if (sourceProperty !== void 0 && sourceProperty !== null) {
switch (propertyType) {
case 0:
serializationObject[targetPropertyName] = sourceProperty;
break;
case 1:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 2:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 3:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 4:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 5:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 6:
serializationObject[targetPropertyName] = sourceProperty.id;
break;
case 7:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 8:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 9:
serializationObject[targetPropertyName] = sourceProperty.serialize();
break;
case 10:
serializationObject[targetPropertyName] = sourceProperty.asArray();
break;
case 11:
serializationObject[targetPropertyName] = sourceProperty.id;
break;
}
}
}
return serializationObject;
};
SerializationHelper2.Parse = function(creationFunction, source, scene, rootUrl) {
if (rootUrl === void 0) {
rootUrl = null;
}
var destination = creationFunction();
if (!rootUrl) {
rootUrl = "";
}
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(destination, source.tags);
}
var classStore = getMergedStore(destination);
for (var property in classStore) {
var propertyDescriptor = classStore[property];
var sourceProperty = source[propertyDescriptor.sourceName || property];
var propertyType = propertyDescriptor.type;
if (sourceProperty !== void 0 && sourceProperty !== null) {
var dest = destination;
switch (propertyType) {
case 0:
dest[property] = sourceProperty;
break;
case 1:
if (scene) {
dest[property] = BABYLON2.Texture.Parse(sourceProperty, scene, rootUrl);
}
break;
case 2:
dest[property] = BABYLON2.Color3.FromArray(sourceProperty);
break;
case 3:
dest[property] = BABYLON2.FresnelParameters.Parse(sourceProperty);
break;
case 4:
dest[property] = BABYLON2.Vector2.FromArray(sourceProperty);
break;
case 5:
dest[property] = BABYLON2.Vector3.FromArray(sourceProperty);
break;
case 6:
if (scene) {
dest[property] = scene.getLastMeshByID(sourceProperty);
}
break;
case 7:
dest[property] = BABYLON2.ColorCurves.Parse(sourceProperty);
break;
case 8:
dest[property] = BABYLON2.Color4.FromArray(sourceProperty);
break;
case 9:
dest[property] = BABYLON2.ImageProcessingConfiguration.Parse(sourceProperty);
break;
case 10:
dest[property] = BABYLON2.Quaternion.FromArray(sourceProperty);
break;
case 11:
if (scene) {
dest[property] = scene.getCameraByID(sourceProperty);
}
break;
}
}
}
return destination;
};
SerializationHelper2.Clone = function(creationFunction, source) {
return _copySource(creationFunction, source, false);
};
SerializationHelper2.Instanciate = function(creationFunction, source) {
return _copySource(creationFunction, source, true);
};
return SerializationHelper2;
}()
);
BABYLON2.SerializationHelper = SerializationHelper;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Deferred = (
/** @class */
function() {
function Deferred2() {
var _this = this;
this.promise = new Promise(function(resolve, reject) {
_this._resolve = resolve;
_this._reject = reject;
});
}
Object.defineProperty(Deferred2.prototype, "resolve", {
/**
* The resolve method of the promise associated with this deferred object.
*/
get: function() {
return this._resolve;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Deferred2.prototype, "reject", {
/**
* The reject method of the promise associated with this deferred object.
*/
get: function() {
return this._reject;
},
enumerable: true,
configurable: true
});
return Deferred2;
}()
);
BABYLON2.Deferred = Deferred;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var EventState = (
/** @class */
function() {
function EventState2(mask, skipNextObservers, target, currentTarget) {
if (skipNextObservers === void 0) {
skipNextObservers = false;
}
this.initalize(mask, skipNextObservers, target, currentTarget);
}
EventState2.prototype.initalize = function(mask, skipNextObservers, target, currentTarget) {
if (skipNextObservers === void 0) {
skipNextObservers = false;
}
this.mask = mask;
this.skipNextObservers = skipNextObservers;
this.target = target;
this.currentTarget = currentTarget;
return this;
};
return EventState2;
}()
);
BABYLON2.EventState = EventState;
var Observer = (
/** @class */
function() {
function Observer2(callback, mask, scope2) {
if (scope2 === void 0) {
scope2 = null;
}
this.callback = callback;
this.mask = mask;
this.scope = scope2;
this._willBeUnregistered = false;
this.unregisterOnNextCall = false;
}
return Observer2;
}()
);
BABYLON2.Observer = Observer;
var MultiObserver = (
/** @class */
function() {
function MultiObserver2() {
}
MultiObserver2.prototype.dispose = function() {
if (this._observers && this._observables) {
for (var index = 0; index < this._observers.length; index++) {
this._observables[index].remove(this._observers[index]);
}
}
this._observers = null;
this._observables = null;
};
MultiObserver2.Watch = function(observables, callback, mask, scope2) {
if (mask === void 0) {
mask = -1;
}
if (scope2 === void 0) {
scope2 = null;
}
var result = new MultiObserver2();
result._observers = new Array();
result._observables = observables;
for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
var observable = observables_1[_i];
var observer2 = observable.add(callback, mask, false, scope2);
if (observer2) {
result._observers.push(observer2);
}
}
return result;
};
return MultiObserver2;
}()
);
BABYLON2.MultiObserver = MultiObserver;
var Observable = (
/** @class */
function() {
function Observable2(onObserverAdded) {
this._observers = new Array();
this._eventState = new EventState(0);
if (onObserverAdded) {
this._onObserverAdded = onObserverAdded;
}
}
Observable2.prototype.add = function(callback, mask, insertFirst, scope2, unregisterOnFirstCall) {
if (mask === void 0) {
mask = -1;
}
if (insertFirst === void 0) {
insertFirst = false;
}
if (scope2 === void 0) {
scope2 = null;
}
if (unregisterOnFirstCall === void 0) {
unregisterOnFirstCall = false;
}
if (!callback) {
return null;
}
var observer2 = new Observer(callback, mask, scope2);
observer2.unregisterOnNextCall = unregisterOnFirstCall;
if (insertFirst) {
this._observers.unshift(observer2);
} else {
this._observers.push(observer2);
}
if (this._onObserverAdded) {
this._onObserverAdded(observer2);
}
return observer2;
};
Observable2.prototype.addOnce = function(callback) {
return this.add(callback, void 0, void 0, void 0, true);
};
Observable2.prototype.remove = function(observer2) {
if (!observer2) {
return false;
}
var index = this._observers.indexOf(observer2);
if (index !== -1) {
this._deferUnregister(observer2);
return true;
}
return false;
};
Observable2.prototype.removeCallback = function(callback, scope2) {
for (var index = 0; index < this._observers.length; index++) {
if (this._observers[index].callback === callback && (!scope2 || scope2 === this._observers[index].scope)) {
this._deferUnregister(this._observers[index]);
return true;
}
}
return false;
};
Observable2.prototype._deferUnregister = function(observer2) {
var _this = this;
observer2.unregisterOnNextCall = false;
observer2._willBeUnregistered = true;
BABYLON2.Tools.SetImmediate(function() {
_this._remove(observer2);
});
};
Observable2.prototype._remove = function(observer2) {
if (!observer2) {
return false;
}
var index = this._observers.indexOf(observer2);
if (index !== -1) {
this._observers.splice(index, 1);
return true;
}
return false;
};
Observable2.prototype.notifyObservers = function(eventData, mask, target, currentTarget) {
if (mask === void 0) {
mask = -1;
}
if (!this._observers.length) {
return true;
}
var state = this._eventState;
state.mask = mask;
state.target = target;
state.currentTarget = currentTarget;
state.skipNextObservers = false;
state.lastReturnValue = eventData;
for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
var obs = _a[_i];
if (obs._willBeUnregistered) {
continue;
}
if (obs.mask & mask) {
if (obs.scope) {
state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
} else {
state.lastReturnValue = obs.callback(eventData, state);
}
if (obs.unregisterOnNextCall) {
this._deferUnregister(obs);
}
}
if (state.skipNextObservers) {
return false;
}
}
return true;
};
Observable2.prototype.notifyObserversWithPromise = function(eventData, mask, target, currentTarget) {
var _this = this;
if (mask === void 0) {
mask = -1;
}
var p = Promise.resolve(eventData);
if (!this._observers.length) {
return p;
}
var state = this._eventState;
state.mask = mask;
state.target = target;
state.currentTarget = currentTarget;
state.skipNextObservers = false;
this._observers.forEach(function(obs) {
if (state.skipNextObservers) {
return;
}
if (obs._willBeUnregistered) {
return;
}
if (obs.mask & mask) {
if (obs.scope) {
p = p.then(function(lastReturnedValue) {
state.lastReturnValue = lastReturnedValue;
return obs.callback.apply(obs.scope, [eventData, state]);
});
} else {
p = p.then(function(lastReturnedValue) {
state.lastReturnValue = lastReturnedValue;
return obs.callback(eventData, state);
});
}
if (obs.unregisterOnNextCall) {
_this._deferUnregister(obs);
}
}
});
return p.then(function() {
return eventData;
});
};
Observable2.prototype.notifyObserver = function(observer2, eventData, mask) {
if (mask === void 0) {
mask = -1;
}
var state = this._eventState;
state.mask = mask;
state.skipNextObservers = false;
observer2.callback(eventData, state);
};
Observable2.prototype.hasObservers = function() {
return this._observers.length > 0;
};
Observable2.prototype.clear = function() {
this._observers = new Array();
this._onObserverAdded = null;
};
Observable2.prototype.clone = function() {
var result = new Observable2();
result._observers = this._observers.slice(0);
return result;
};
Observable2.prototype.hasSpecificMask = function(mask) {
if (mask === void 0) {
mask = -1;
}
for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
var obs = _a[_i];
if (obs.mask & mask || obs.mask === mask) {
return true;
}
}
return false;
};
return Observable2;
}()
);
BABYLON2.Observable = Observable;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SmartArray = (
/** @class */
function() {
function SmartArray2(capacity) {
this.length = 0;
this.data = new Array(capacity);
this._id = SmartArray2._GlobalId++;
}
SmartArray2.prototype.push = function(value) {
this.data[this.length++] = value;
if (this.length > this.data.length) {
this.data.length *= 2;
}
};
SmartArray2.prototype.forEach = function(func) {
for (var index = 0; index < this.length; index++) {
func(this.data[index]);
}
};
SmartArray2.prototype.sort = function(compareFn) {
this.data.sort(compareFn);
};
SmartArray2.prototype.reset = function() {
this.length = 0;
};
SmartArray2.prototype.dispose = function() {
this.reset();
if (this.data) {
this.data.length = 0;
this.data = [];
}
};
SmartArray2.prototype.concat = function(array) {
if (array.length === 0) {
return;
}
if (this.length + array.length > this.data.length) {
this.data.length = (this.length + array.length) * 2;
}
for (var index = 0; index < array.length; index++) {
this.data[this.length++] = (array.data || array)[index];
}
};
SmartArray2.prototype.indexOf = function(value) {
var position = this.data.indexOf(value);
if (position >= this.length) {
return -1;
}
return position;
};
SmartArray2.prototype.contains = function(value) {
return this.indexOf(value) !== -1;
};
SmartArray2._GlobalId = 0;
return SmartArray2;
}()
);
BABYLON2.SmartArray = SmartArray;
var SmartArrayNoDuplicate = (
/** @class */
function(_super) {
__extends(SmartArrayNoDuplicate2, _super);
function SmartArrayNoDuplicate2() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._duplicateId = 0;
return _this;
}
SmartArrayNoDuplicate2.prototype.push = function(value) {
_super.prototype.push.call(this, value);
if (!value.__smartArrayFlags) {
value.__smartArrayFlags = {};
}
value.__smartArrayFlags[this._id] = this._duplicateId;
};
SmartArrayNoDuplicate2.prototype.pushNoDuplicate = function(value) {
if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
return false;
}
this.push(value);
return true;
};
SmartArrayNoDuplicate2.prototype.reset = function() {
_super.prototype.reset.call(this);
this._duplicateId++;
};
SmartArrayNoDuplicate2.prototype.concatWithNoDuplicate = function(array) {
if (array.length === 0) {
return;
}
if (this.length + array.length > this.data.length) {
this.data.length = (this.length + array.length) * 2;
}
for (var index = 0; index < array.length; index++) {
var item = (array.data || array)[index];
this.pushNoDuplicate(item);
}
};
return SmartArrayNoDuplicate2;
}(SmartArray)
);
BABYLON2.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ColorGradient = (
/** @class */
function() {
function ColorGradient2() {
}
ColorGradient2.prototype.getColorToRef = function(result) {
if (!this.color2) {
result.copyFrom(this.color1);
return;
}
BABYLON2.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
};
return ColorGradient2;
}()
);
BABYLON2.ColorGradient = ColorGradient;
var Color3Gradient = (
/** @class */
function() {
function Color3Gradient2() {
}
return Color3Gradient2;
}()
);
BABYLON2.Color3Gradient = Color3Gradient;
var FactorGradient = (
/** @class */
function() {
function FactorGradient2() {
}
FactorGradient2.prototype.getFactor = function() {
if (this.factor2 === void 0) {
return this.factor1;
}
return BABYLON2.Scalar.Lerp(this.factor1, this.factor2, Math.random());
};
return FactorGradient2;
}()
);
BABYLON2.FactorGradient = FactorGradient;
var LoadFileError = (
/** @class */
function(_super) {
__extends(LoadFileError2, _super);
function LoadFileError2(message, request) {
var _this = _super.call(this, message) || this;
_this.request = request;
_this.name = "LoadFileError";
LoadFileError2._setPrototypeOf(_this, LoadFileError2.prototype);
return _this;
}
LoadFileError2._setPrototypeOf = Object.setPrototypeOf || function(o, proto) {
o.__proto__ = proto;
return o;
};
return LoadFileError2;
}(Error)
);
BABYLON2.LoadFileError = LoadFileError;
var RetryStrategy = (
/** @class */
function() {
function RetryStrategy2() {
}
RetryStrategy2.ExponentialBackoff = function(maxRetries, baseInterval) {
if (maxRetries === void 0) {
maxRetries = 3;
}
if (baseInterval === void 0) {
baseInterval = 500;
}
return function(url, request, retryIndex) {
if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
return -1;
}
return Math.pow(2, retryIndex) * baseInterval;
};
};
return RetryStrategy2;
}()
);
BABYLON2.RetryStrategy = RetryStrategy;
var screenshotCanvas;
var cloneValue = function(source, destinationObject) {
if (!source) {
return null;
}
if (source instanceof BABYLON2.Mesh) {
return null;
}
if (source instanceof BABYLON2.SubMesh) {
return source.clone(destinationObject);
} else if (source.clone) {
return source.clone();
}
return null;
};
var Tools = (
/** @class */
function() {
function Tools2() {
}
Tools2.FetchToRef = function(u, v, width, height, pixels, color) {
var wrappedU = Math.abs(u) * width % width | 0;
var wrappedV = Math.abs(v) * height % height | 0;
var position = (wrappedU + wrappedV * width) * 4;
color.r = pixels[position] / 255;
color.g = pixels[position + 1] / 255;
color.b = pixels[position + 2] / 255;
color.a = pixels[position + 3] / 255;
};
Tools2.Mix = function(a, b2, alpha) {
return a * (1 - alpha) + b2 * alpha;
};
Tools2.Instantiate = function(className2) {
if (Tools2.RegisteredExternalClasses && Tools2.RegisteredExternalClasses[className2]) {
return Tools2.RegisteredExternalClasses[className2];
}
var arr = className2.split(".");
var fn = window || this;
for (var i2 = 0, len = arr.length; i2 < len; i2++) {
fn = fn[arr[i2]];
}
if (typeof fn !== "function") {
return null;
}
return fn;
};
Tools2.Slice = function(data2, start, end) {
if (data2.slice) {
return data2.slice(start, end);
}
return Array.prototype.slice.call(data2, start, end);
};
Tools2.SetImmediate = function(action) {
if (Tools2.IsWindowObjectExist() && window.setImmediate) {
window.setImmediate(action);
} else {
setTimeout(action, 1);
}
};
Tools2.IsExponentOfTwo = function(value) {
var count = 1;
do {
count *= 2;
} while (count < value);
return count === value;
};
Tools2.FloatRound = function(value) {
if (Math.fround) {
return Math.fround(value);
}
return Tools2._tmpFloatArray[0] = value;
};
Tools2.CeilingPOT = function(x) {
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
};
Tools2.FloorPOT = function(x) {
x = x | x >> 1;
x = x | x >> 2;
x = x | x >> 4;
x = x | x >> 8;
x = x | x >> 16;
return x - (x >> 1);
};
Tools2.NearestPOT = function(x) {
var c = Tools2.CeilingPOT(x);
var f = Tools2.FloorPOT(x);
return c - x > x - f ? f : c;
};
Tools2.GetExponentOfTwo = function(value, max, mode) {
if (mode === void 0) {
mode = BABYLON2.Engine.SCALEMODE_NEAREST;
}
var pot;
switch (mode) {
case BABYLON2.Engine.SCALEMODE_FLOOR:
pot = Tools2.FloorPOT(value);
break;
case BABYLON2.Engine.SCALEMODE_NEAREST:
pot = Tools2.NearestPOT(value);
break;
case BABYLON2.Engine.SCALEMODE_CEILING:
default:
pot = Tools2.CeilingPOT(value);
break;
}
return Math.min(pot, max);
};
Tools2.GetFilename = function(path) {
var index = path.lastIndexOf("/");
if (index < 0) {
return path;
}
return path.substring(index + 1);
};
Tools2.GetFolderPath = function(uri, returnUnchangedIfNoSlash) {
if (returnUnchangedIfNoSlash === void 0) {
returnUnchangedIfNoSlash = false;
}
var index = uri.lastIndexOf("/");
if (index < 0) {
if (returnUnchangedIfNoSlash) {
return uri;
}
return "";
}
return uri.substring(0, index + 1);
};
Tools2.GetDOMTextContent = function(element) {
var result = "";
var child = element.firstChild;
while (child) {
if (child.nodeType === 3) {
result += child.textContent;
}
child = child.nextSibling;
}
return result;
};
Tools2.ToDegrees = function(angle) {
return angle * 180 / Math.PI;
};
Tools2.ToRadians = function(angle) {
return angle * Math.PI / 180;
};
Tools2.EncodeArrayBufferTobase64 = function(buffer) {
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i2 = 0;
var bytes = new Uint8Array(buffer);
while (i2 < bytes.length) {
chr1 = bytes[i2++];
chr2 = i2 < bytes.length ? bytes[i2++] : Number.NaN;
chr3 = i2 < bytes.length ? bytes[i2++] : Number.NaN;
enc1 = chr1 >> 2;
enc2 = (chr1 & 3) << 4 | chr2 >> 4;
enc3 = (chr2 & 15) << 2 | chr3 >> 6;
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
}
return "data:image/png;base64," + output;
};
Tools2.ExtractMinAndMaxIndexed = function(positions, indices, indexStart, indexCount, bias) {
if (bias === void 0) {
bias = null;
}
var minimum = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var maximum = new BABYLON2.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
for (var index = indexStart; index < indexStart + indexCount; index++) {
var offset = indices[index] * 3;
var x = positions[offset];
var y = positions[offset + 1];
var z = positions[offset + 2];
minimum.minimizeInPlaceFromFloats(x, y, z);
maximum.maximizeInPlaceFromFloats(x, y, z);
}
if (bias) {
minimum.x -= minimum.x * bias.x + bias.y;
minimum.y -= minimum.y * bias.x + bias.y;
minimum.z -= minimum.z * bias.x + bias.y;
maximum.x += maximum.x * bias.x + bias.y;
maximum.y += maximum.y * bias.x + bias.y;
maximum.z += maximum.z * bias.x + bias.y;
}
return {
minimum,
maximum
};
};
Tools2.ExtractMinAndMax = function(positions, start, count, bias, stride) {
if (bias === void 0) {
bias = null;
}
var minimum = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var maximum = new BABYLON2.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
if (!stride) {
stride = 3;
}
for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
var x = positions[offset];
var y = positions[offset + 1];
var z = positions[offset + 2];
minimum.minimizeInPlaceFromFloats(x, y, z);
maximum.maximizeInPlaceFromFloats(x, y, z);
}
if (bias) {
minimum.x -= minimum.x * bias.x + bias.y;
minimum.y -= minimum.y * bias.x + bias.y;
minimum.z -= minimum.z * bias.x + bias.y;
maximum.x += maximum.x * bias.x + bias.y;
maximum.y += maximum.y * bias.x + bias.y;
maximum.z += maximum.z * bias.x + bias.y;
}
return {
minimum,
maximum
};
};
Tools2.MakeArray = function(obj, allowsNullUndefined) {
if (allowsNullUndefined !== true && (obj === void 0 || obj == null)) {
return null;
}
return Array.isArray(obj) ? obj : [obj];
};
Tools2.GetPointerPrefix = function() {
var eventPrefix = "pointer";
if (Tools2.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
eventPrefix = "mouse";
}
return eventPrefix;
};
Tools2.QueueNewFrame = function(func, requester) {
if (BABYLON2.chrome84BugWorkaround) {
return setTimeout(() => requestAnimationFrame(func), 0);
}
if (!Tools2.IsWindowObjectExist()) {
return window.setTimeout(func, 16);
}
if (!requester) {
requester = window;
}
if (requester.requestAnimationFrame) {
return requester.requestAnimationFrame(func);
} else if (requester.msRequestAnimationFrame) {
return requester.msRequestAnimationFrame(func);
} else if (requester.webkitRequestAnimationFrame) {
return requester.webkitRequestAnimationFrame(func);
} else if (requester.mozRequestAnimationFrame) {
return requester.mozRequestAnimationFrame(func);
} else if (requester.oRequestAnimationFrame) {
return requester.oRequestAnimationFrame(func);
} else {
return window.setTimeout(func, 16);
}
};
Tools2.RequestFullscreen = function(element) {
var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
if (!requestFunction) {
return;
}
requestFunction.call(element);
};
Tools2.ExitFullscreen = function() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.msCancelFullScreen) {
document.msCancelFullScreen();
}
};
Tools2.SetCorsBehavior = function(url, element) {
if (url && url.indexOf("data:") === 0) {
return;
}
if (Tools2.CorsBehavior) {
if (typeof Tools2.CorsBehavior === "string" || Tools2.CorsBehavior instanceof String) {
element.crossOrigin = Tools2.CorsBehavior;
} else {
var result = Tools2.CorsBehavior(url);
if (result) {
element.crossOrigin = result;
}
}
}
};
Tools2.CleanUrl = function(url) {
url = url.replace(/#/mg, "%23");
return url;
};
Tools2.LoadImage = function(input, onLoad, onError, database) {
var url;
var usingObjectURL = false;
if (input instanceof ArrayBuffer) {
url = URL.createObjectURL(new Blob([input]));
usingObjectURL = true;
} else if (input instanceof Blob) {
url = URL.createObjectURL(input);
usingObjectURL = true;
} else {
url = Tools2.CleanUrl(input);
url = Tools2.PreprocessUrl(input);
}
var img = new Image();
Tools2.SetCorsBehavior(url, img);
var loadHandler = function() {
if (usingObjectURL && img.src) {
URL.revokeObjectURL(img.src);
}
img.removeEventListener("load", loadHandler);
img.removeEventListener("error", errorHandler);
onLoad(img);
};
var errorHandler = function(err) {
if (usingObjectURL && img.src) {
URL.revokeObjectURL(img.src);
}
img.removeEventListener("load", loadHandler);
img.removeEventListener("error", errorHandler);
Tools2.Error("Error while trying to load image: " + input);
if (onError) {
onError("Error while trying to load image: " + input, err);
}
};
img.addEventListener("load", loadHandler);
img.addEventListener("error", errorHandler);
var noIndexedDB = function() {
img.src = url;
};
var loadFromIndexedDB = function() {
if (database) {
database.loadImageFromDB(url, img);
}
};
if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON2.Database.IsUASupportingBlobStorage) {
database.openAsync(loadFromIndexedDB, noIndexedDB);
} else {
if (url.indexOf("file:") !== -1) {
var textureName = decodeURIComponent(url.substring(5).toLowerCase());
if (BABYLON2.FilesInput.FilesToLoad[textureName]) {
try {
var blobURL2;
try {
blobURL2 = URL.createObjectURL(BABYLON2.FilesInput.FilesToLoad[textureName]);
} catch (ex) {
blobURL2 = URL.createObjectURL(BABYLON2.FilesInput.FilesToLoad[textureName]);
}
img.src = blobURL2;
usingObjectURL = true;
} catch (e2) {
img.src = "";
}
return img;
}
}
noIndexedDB();
}
return img;
};
Tools2.LoadFile = function(url, onSuccess, onProgress, database, useArrayBuffer, onError) {
url = Tools2.CleanUrl(url);
url = Tools2.PreprocessUrl(url);
if (url.indexOf("file:") !== -1) {
var fileName = decodeURIComponent(url.substring(5).toLowerCase());
if (BABYLON2.FilesInput.FilesToLoad[fileName]) {
return Tools2.ReadFile(BABYLON2.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
}
}
var loadUrl = Tools2.BaseUrl + url;
var aborted = false;
var fileRequest = {
onCompleteObservable: new BABYLON2.Observable(),
abort: function() {
return aborted = true;
}
};
var requestFile = function() {
var request = new XMLHttpRequest();
var retryHandle = null;
fileRequest.abort = function() {
aborted = true;
if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
request.abort();
}
if (retryHandle !== null) {
clearTimeout(retryHandle);
retryHandle = null;
}
};
var retryLoop = function(retryIndex) {
request.open("GET", loadUrl, true);
if (useArrayBuffer) {
request.responseType = "arraybuffer";
}
if (onProgress) {
request.addEventListener("progress", onProgress);
}
var onLoadEnd = function() {
request.removeEventListener("loadend", onLoadEnd);
fileRequest.onCompleteObservable.notifyObservers(fileRequest);
fileRequest.onCompleteObservable.clear();
};
request.addEventListener("loadend", onLoadEnd);
var onReadyStateChange = function() {
if (aborted) {
return;
}
if (request.readyState === (XMLHttpRequest.DONE || 4)) {
request.removeEventListener("readystatechange", onReadyStateChange);
if (request.status >= 200 && request.status < 300 || request.status === 0 && (!Tools2.IsWindowObjectExist() || Tools2.IsFileURL())) {
onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
return;
}
var retryStrategy = Tools2.DefaultRetryStrategy;
if (retryStrategy) {
var waitTime = retryStrategy(loadUrl, request, retryIndex);
if (waitTime !== -1) {
request.removeEventListener("loadend", onLoadEnd);
request = new XMLHttpRequest();
retryHandle = setTimeout(function() {
return retryLoop(retryIndex + 1);
}, waitTime);
return;
}
}
var e2 = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
if (onError) {
onError(request, e2);
} else {
throw e2;
}
}
};
request.addEventListener("readystatechange", onReadyStateChange);
request.send();
};
retryLoop(0);
};
if (database && database.enableSceneOffline) {
var noIndexedDB_1 = function(request) {
if (request && request.status > 400) {
if (onError) {
onError(request);
}
} else {
if (!aborted) {
requestFile();
}
}
};
var loadFromIndexedDB = function() {
if (aborted) {
return;
}
if (database) {
database.loadFileFromDB(url, function(data2) {
if (!aborted) {
onSuccess(data2);
}
fileRequest.onCompleteObservable.notifyObservers(fileRequest);
}, onProgress ? function(event) {
if (!aborted) {
onProgress(event);
}
} : void 0, noIndexedDB_1, useArrayBuffer);
}
};
database.openAsync(loadFromIndexedDB, noIndexedDB_1);
} else {
requestFile();
}
return fileRequest;
};
Tools2.LoadScript = function(scriptUrl, onSuccess, onError) {
if (!Tools2.IsWindowObjectExist()) {
return;
}
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = scriptUrl;
script.onload = function() {
if (onSuccess) {
onSuccess();
}
};
script.onerror = function(e2) {
if (onError) {
onError("Unable to load script '" + scriptUrl + "'", e2);
}
};
head.appendChild(script);
};
Tools2.ReadFileAsDataURL = function(fileToLoad, callback, progressCallback) {
var reader = new FileReader();
var request = {
onCompleteObservable: new BABYLON2.Observable(),
abort: function() {
return reader.abort();
}
};
reader.onloadend = function(e2) {
request.onCompleteObservable.notifyObservers(request);
};
reader.onload = function(e2) {
callback(e2.target["result"]);
};
reader.onprogress = progressCallback;
reader.readAsDataURL(fileToLoad);
return request;
};
Tools2.ReadFile = function(fileToLoad, callback, progressCallBack, useArrayBuffer) {
var reader = new FileReader();
var request = {
onCompleteObservable: new BABYLON2.Observable(),
abort: function() {
return reader.abort();
}
};
reader.onloadend = function(e2) {
return request.onCompleteObservable.notifyObservers(request);
};
reader.onerror = function(e2) {
Tools2.Log("Error while reading file: " + fileToLoad.name);
callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
};
reader.onload = function(e2) {
callback(e2.target["result"]);
};
if (progressCallBack) {
reader.onprogress = progressCallBack;
}
if (!useArrayBuffer) {
reader.readAsText(fileToLoad);
} else {
reader.readAsArrayBuffer(fileToLoad);
}
return request;
};
Tools2.FileAsURL = function(content) {
var fileBlob = new Blob([content]);
var url = window.URL || window.webkitURL;
var link = url.createObjectURL(fileBlob);
return link;
};
Tools2.Format = function(value, decimals) {
if (decimals === void 0) {
decimals = 2;
}
return value.toFixed(decimals);
};
Tools2.CheckExtends = function(v, min, max) {
if (v.x < min.x) {
min.x = v.x;
}
if (v.y < min.y) {
min.y = v.y;
}
if (v.z < min.z) {
min.z = v.z;
}
if (v.x > max.x) {
max.x = v.x;
}
if (v.y > max.y) {
max.y = v.y;
}
if (v.z > max.z) {
max.z = v.z;
}
};
Tools2.DeepCopy = function(source, destination, doNotCopyList, mustCopyList) {
for (var prop in source) {
if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
continue;
}
if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
continue;
}
var sourceValue = source[prop];
var typeOfSourceValue = typeof sourceValue;
if (typeOfSourceValue === "function") {
continue;
}
try {
if (typeOfSourceValue === "object") {
if (sourceValue instanceof Array) {
destination[prop] = [];
if (sourceValue.length > 0) {
if (typeof sourceValue[0] == "object") {
for (var index = 0; index < sourceValue.length; index++) {
var clonedValue = cloneValue(sourceValue[index], destination);
if (destination[prop].indexOf(clonedValue) === -1) {
destination[prop].push(clonedValue);
}
}
} else {
destination[prop] = sourceValue.slice(0);
}
}
} else {
destination[prop] = cloneValue(sourceValue, destination);
}
} else {
destination[prop] = sourceValue;
}
} catch (e2) {
}
}
};
Tools2.IsEmpty = function(obj) {
for (var i2 in obj) {
if (obj.hasOwnProperty(i2)) {
return false;
}
}
return true;
};
Tools2.RegisterTopRootEvents = function(events) {
for (var index = 0; index < events.length; index++) {
var event = events[index];
window.addEventListener(event.name, event.handler, false);
try {
if (window.parent) {
window.parent.addEventListener(event.name, event.handler, false);
}
} catch (e2) {
}
}
};
Tools2.UnregisterTopRootEvents = function(events) {
for (var index = 0; index < events.length; index++) {
var event = events[index];
window.removeEventListener(event.name, event.handler);
try {
if (window.parent) {
window.parent.removeEventListener(event.name, event.handler);
}
} catch (e2) {
}
}
};
Tools2.DumpFramebuffer = function(width, height, engine, successCallback2, mimeType, fileName) {
if (mimeType === void 0) {
mimeType = "image/png";
}
var numberOfChannelsByLine = width * 4;
var halfHeight = height / 2;
var data2 = engine.readPixels(0, 0, width, height);
for (var i2 = 0; i2 < halfHeight; i2++) {
for (var j = 0; j < numberOfChannelsByLine; j++) {
var currentCell = j + i2 * numberOfChannelsByLine;
var targetLine = height - i2 - 1;
var targetCell = j + targetLine * numberOfChannelsByLine;
var temp = data2[currentCell];
data2[currentCell] = data2[targetCell];
data2[targetCell] = temp;
}
}
if (!screenshotCanvas) {
screenshotCanvas = document.createElement("canvas");
}
screenshotCanvas.width = width;
screenshotCanvas.height = height;
var context = screenshotCanvas.getContext("2d");
if (context) {
var imageData = context.createImageData(width, height);
var castData = imageData.data;
castData.set(data2);
context.putImageData(imageData, 0, 0);
Tools2.EncodeScreenshotCanvasData(successCallback2, mimeType, fileName);
}
};
Tools2.ToBlob = function(canvas2, successCallback2, mimeType) {
if (mimeType === void 0) {
mimeType = "image/png";
}
if (!canvas2.toBlob) {
canvas2.toBlob = function(callback, type, quality) {
var _this = this;
setTimeout(function() {
var binStr = atob(_this.toDataURL(type, quality).split(",")[1]), len = binStr.length, arr = new Uint8Array(len);
for (var i2 = 0; i2 < len; i2++) {
arr[i2] = binStr.charCodeAt(i2);
}
callback(new Blob([arr]));
});
};
}
canvas2.toBlob(function(blob2) {
successCallback2(blob2);
}, mimeType);
};
Tools2.EncodeScreenshotCanvasData = function(successCallback2, mimeType, fileName) {
if (mimeType === void 0) {
mimeType = "image/png";
}
if (successCallback2) {
var base64Image = screenshotCanvas.toDataURL(mimeType);
successCallback2(base64Image);
} else {
this.ToBlob(screenshotCanvas, function(blob2) {
if ("download" in document.createElement("a")) {
if (!fileName) {
var date = /* @__PURE__ */ new Date();
var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ("0" + date.getMinutes()).slice(-2);
fileName = "screenshot_" + stringDate + ".png";
}
Tools2.Download(blob2, fileName);
} else {
var url = URL.createObjectURL(blob2);
var newWindow = window.open("");
if (!newWindow) {
return;
}
var img = newWindow.document.createElement("img");
img.onload = function() {
URL.revokeObjectURL(url);
};
img.src = url;
newWindow.document.body.appendChild(img);
}
}, mimeType);
}
};
Tools2.Download = function(blob2, fileName) {
if (navigator && navigator.msSaveBlob) {
navigator.msSaveBlob(blob2, fileName);
return;
}
var url = window.URL.createObjectURL(blob2);
var a = document.createElement("a");
document.body.appendChild(a);
a.style.display = "none";
a.href = url;
a.download = fileName;
a.addEventListener("click", function() {
if (a.parentElement) {
a.parentElement.removeChild(a);
}
});
a.click();
window.URL.revokeObjectURL(url);
};
Tools2.CreateScreenshot = function(engine, camera2, size, successCallback2, mimeType) {
if (mimeType === void 0) {
mimeType = "image/png";
}
var width;
var height;
if (size.precision) {
width = Math.round(engine.getRenderWidth() * size.precision);
height = Math.round(width / engine.getAspectRatio(camera2));
} else if (size.width && size.height) {
width = size.width;
height = size.height;
} else if (size.width && !size.height) {
width = size.width;
height = Math.round(width / engine.getAspectRatio(camera2));
} else if (size.height && !size.width) {
height = size.height;
width = Math.round(height * engine.getAspectRatio(camera2));
} else if (!isNaN(size)) {
height = size;
width = size;
} else {
Tools2.Error("Invalid 'size' parameter !");
return;
}
if (!screenshotCanvas) {
screenshotCanvas = document.createElement("canvas");
}
screenshotCanvas.width = width;
screenshotCanvas.height = height;
var renderContext = screenshotCanvas.getContext("2d");
var ratio = engine.getRenderWidth() / engine.getRenderHeight();
var newWidth = width;
var newHeight = newWidth / ratio;
if (newHeight > height) {
newHeight = height;
newWidth = newHeight * ratio;
}
var offsetX = Math.max(0, width - newWidth) / 2;
var offsetY = Math.max(0, height - newHeight) / 2;
var renderingCanvas = engine.getRenderingCanvas();
if (renderContext && renderingCanvas) {
renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
}
Tools2.EncodeScreenshotCanvasData(successCallback2, mimeType);
};
Tools2.CreateScreenshotUsingRenderTarget = function(engine, camera2, size, successCallback2, mimeType, samples, antialiasing, fileName) {
if (mimeType === void 0) {
mimeType = "image/png";
}
if (samples === void 0) {
samples = 1;
}
if (antialiasing === void 0) {
antialiasing = false;
}
var width;
var height;
if (size.precision) {
width = Math.round(engine.getRenderWidth() * size.precision);
height = Math.round(width / engine.getAspectRatio(camera2));
size = { width, height };
} else if (size.width && size.height) {
width = size.width;
height = size.height;
} else if (size.width && !size.height) {
width = size.width;
height = Math.round(width / engine.getAspectRatio(camera2));
size = { width, height };
} else if (size.height && !size.width) {
height = size.height;
width = Math.round(height * engine.getAspectRatio(camera2));
size = { width, height };
} else if (!isNaN(size)) {
height = size;
width = size;
} else {
Tools2.Error("Invalid 'size' parameter !");
return;
}
var scene = camera2.getScene();
var previousCamera = null;
if (scene.activeCamera !== camera2) {
previousCamera = scene.activeCamera;
scene.activeCamera = camera2;
}
var texture = new BABYLON2.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON2.Texture.NEAREST_SAMPLINGMODE);
texture.renderList = null;
texture.samples = samples;
if (antialiasing) {
texture.addPostProcess(new BABYLON2.FxaaPostProcess("antialiasing", 1, scene.activeCamera));
}
texture.onAfterRenderObservable.add(function() {
Tools2.DumpFramebuffer(width, height, engine, successCallback2, mimeType, fileName);
});
scene.incrementRenderId();
scene.resetCachedMaterial();
texture.render(true);
texture.dispose();
if (previousCamera) {
scene.activeCamera = previousCamera;
}
camera2.getProjectionMatrix(true);
};
Tools2.ValidateXHRData = function(xhr, dataType) {
if (dataType === void 0) {
dataType = 7;
}
try {
if (dataType & 1) {
if (xhr.responseText && xhr.responseText.length > 0) {
return true;
} else if (dataType === 1) {
return false;
}
}
if (dataType & 2) {
var tgaHeader = BABYLON2.TGATools.GetTGAHeader(xhr.response);
if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
return true;
} else if (dataType === 2) {
return false;
}
}
if (dataType & 4) {
var ddsHeader = new Uint8Array(xhr.response, 0, 3);
if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
return true;
} else {
return false;
}
}
} catch (e2) {
}
return false;
};
Tools2.RandomId = function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c === "x" ? r : r & 3 | 8;
return v.toString(16);
});
};
Tools2.IsBase64 = function(uri) {
return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
};
Tools2.DecodeBase64 = function(uri) {
var decodedString = atob(uri.split(",")[1]);
var bufferLength = decodedString.length;
var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
for (var i2 = 0; i2 < bufferLength; i2++) {
bufferView[i2] = decodedString.charCodeAt(i2);
}
return bufferView.buffer;
};
Tools2._AddLogEntry = function(entry) {
Tools2._LogCache = entry + Tools2._LogCache;
if (Tools2.OnNewCacheEntry) {
Tools2.OnNewCacheEntry(entry);
}
};
Tools2._FormatMessage = function(message) {
var padStr = function(i2) {
return i2 < 10 ? "0" + i2 : "" + i2;
};
var date = /* @__PURE__ */ new Date();
return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
};
Tools2._LogDisabled = function(message) {
};
Tools2._LogEnabled = function(message) {
var formattedMessage = Tools2._FormatMessage(message);
console.log("BJS - " + formattedMessage);
var entry = "
" + formattedMessage + "
";
Tools2._AddLogEntry(entry);
};
Tools2._WarnDisabled = function(message) {
};
Tools2._WarnEnabled = function(message) {
var formattedMessage = Tools2._FormatMessage(message);
console.warn("BJS - " + formattedMessage);
var entry = "" + formattedMessage + "
";
Tools2._AddLogEntry(entry);
};
Tools2._ErrorDisabled = function(message) {
};
Tools2._ErrorEnabled = function(message) {
Tools2.errorsCount++;
var formattedMessage = Tools2._FormatMessage(message);
console.error("BJS - " + formattedMessage);
var entry = "" + formattedMessage + "
";
Tools2._AddLogEntry(entry);
};
Object.defineProperty(Tools2, "LogCache", {
/**
* Gets current log cache (list of logs)
*/
get: function() {
return Tools2._LogCache;
},
enumerable: true,
configurable: true
});
Tools2.ClearLogCache = function() {
Tools2._LogCache = "";
Tools2.errorsCount = 0;
};
Object.defineProperty(Tools2, "LogLevels", {
/**
* Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
*/
set: function(level) {
if ((level & Tools2.MessageLogLevel) === Tools2.MessageLogLevel) {
Tools2.Log = Tools2._LogEnabled;
} else {
Tools2.Log = Tools2._LogDisabled;
}
if ((level & Tools2.WarningLogLevel) === Tools2.WarningLogLevel) {
Tools2.Warn = Tools2._WarnEnabled;
} else {
Tools2.Warn = Tools2._WarnDisabled;
}
if ((level & Tools2.ErrorLogLevel) === Tools2.ErrorLogLevel) {
Tools2.Error = Tools2._ErrorEnabled;
} else {
Tools2.Error = Tools2._ErrorDisabled;
}
},
enumerable: true,
configurable: true
});
Tools2.IsFileURL = function() {
return location.protocol === "file:";
};
Tools2.IsWindowObjectExist = function() {
return typeof window !== "undefined";
};
Object.defineProperty(Tools2, "PerformanceLogLevel", {
/**
* Sets the current performance log level
*/
set: function(level) {
if ((level & Tools2.PerformanceUserMarkLogLevel) === Tools2.PerformanceUserMarkLogLevel) {
Tools2.StartPerformanceCounter = Tools2._StartUserMark;
Tools2.EndPerformanceCounter = Tools2._EndUserMark;
return;
}
if ((level & Tools2.PerformanceConsoleLogLevel) === Tools2.PerformanceConsoleLogLevel) {
Tools2.StartPerformanceCounter = Tools2._StartPerformanceConsole;
Tools2.EndPerformanceCounter = Tools2._EndPerformanceConsole;
return;
}
Tools2.StartPerformanceCounter = Tools2._StartPerformanceCounterDisabled;
Tools2.EndPerformanceCounter = Tools2._EndPerformanceCounterDisabled;
},
enumerable: true,
configurable: true
});
Tools2._StartPerformanceCounterDisabled = function(counterName, condition) {
};
Tools2._EndPerformanceCounterDisabled = function(counterName, condition) {
};
Tools2._StartUserMark = function(counterName, condition) {
if (condition === void 0) {
condition = true;
}
if (!Tools2._performance) {
if (!Tools2.IsWindowObjectExist()) {
return;
}
Tools2._performance = window.performance;
}
if (!condition || !Tools2._performance.mark) {
return;
}
Tools2._performance.mark(counterName + "-Begin");
};
Tools2._EndUserMark = function(counterName, condition) {
if (condition === void 0) {
condition = true;
}
if (!condition || !Tools2._performance.mark) {
return;
}
Tools2._performance.mark(counterName + "-End");
Tools2._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
};
Tools2._StartPerformanceConsole = function(counterName, condition) {
if (condition === void 0) {
condition = true;
}
if (!condition) {
return;
}
Tools2._StartUserMark(counterName, condition);
if (console.time) {
console.time(counterName);
}
};
Tools2._EndPerformanceConsole = function(counterName, condition) {
if (condition === void 0) {
condition = true;
}
if (!condition) {
return;
}
Tools2._EndUserMark(counterName, condition);
if (console.time) {
console.timeEnd(counterName);
}
};
Object.defineProperty(Tools2, "Now", {
/**
* Gets either window.performance.now() if supported or Date.now() else
*/
get: function() {
if (Tools2.IsWindowObjectExist() && window.performance && window.performance.now) {
return window.performance.now();
}
return Date.now();
},
enumerable: true,
configurable: true
});
Tools2.GetClassName = function(object, isType) {
if (isType === void 0) {
isType = false;
}
var name = null;
if (!isType && object.getClassName) {
name = object.getClassName();
} else {
if (object instanceof Object) {
var classObj = isType ? object : Object.getPrototypeOf(object);
name = classObj.constructor["__bjsclassName__"];
}
if (!name) {
name = typeof object;
}
}
return name;
};
Tools2.First = function(array, predicate) {
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var el = array_1[_i];
if (predicate(el)) {
return el;
}
}
return null;
};
Tools2.getFullClassName = function(object, isType) {
if (isType === void 0) {
isType = false;
}
var className2 = null;
var moduleName = null;
if (!isType && object.getClassName) {
className2 = object.getClassName();
} else {
if (object instanceof Object) {
var classObj = isType ? object : Object.getPrototypeOf(object);
className2 = classObj.constructor["__bjsclassName__"];
moduleName = classObj.constructor["__bjsmoduleName__"];
}
if (!className2) {
className2 = typeof object;
}
}
if (!className2) {
return null;
}
return (moduleName != null ? moduleName + "." : "") + className2;
};
Tools2.DelayAsync = function(delay) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, delay);
});
};
Tools2.GetCurrentGradient = function(ratio, gradients, updateFunc) {
for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
var currentGradient = gradients[gradientIndex];
var nextGradient = gradients[gradientIndex + 1];
if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
updateFunc(currentGradient, nextGradient, scale);
return;
}
}
var lastIndex = gradients.length - 1;
updateFunc(gradients[lastIndex], gradients[lastIndex], 1);
};
Tools2.BaseUrl = "";
Tools2.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
Tools2.CorsBehavior = "anonymous";
Tools2.UseFallbackTexture = true;
Tools2.RegisteredExternalClasses = {};
Tools2.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
Tools2._tmpFloatArray = new Float32Array(1);
Tools2.PreprocessUrl = function(url) {
return url;
};
Tools2.NoneLogLevel = 0;
Tools2.MessageLogLevel = 1;
Tools2.WarningLogLevel = 2;
Tools2.ErrorLogLevel = 4;
Tools2.AllLogLevel = 7;
Tools2._LogCache = "";
Tools2.errorsCount = 0;
Tools2.Log = Tools2._LogEnabled;
Tools2.Warn = Tools2._WarnEnabled;
Tools2.Error = Tools2._ErrorEnabled;
Tools2.PerformanceNoneLogLevel = 0;
Tools2.PerformanceUserMarkLogLevel = 1;
Tools2.PerformanceConsoleLogLevel = 2;
Tools2.StartPerformanceCounter = Tools2._StartPerformanceCounterDisabled;
Tools2.EndPerformanceCounter = Tools2._EndPerformanceCounterDisabled;
return Tools2;
}()
);
BABYLON2.Tools = Tools;
var PerfCounter = (
/** @class */
function() {
function PerfCounter2() {
this._startMonitoringTime = 0;
this._min = 0;
this._max = 0;
this._average = 0;
this._lastSecAverage = 0;
this._current = 0;
this._totalValueCount = 0;
this._totalAccumulated = 0;
this._lastSecAccumulated = 0;
this._lastSecTime = 0;
this._lastSecValueCount = 0;
}
Object.defineProperty(PerfCounter2.prototype, "min", {
/**
* Returns the smallest value ever
*/
get: function() {
return this._min;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter2.prototype, "max", {
/**
* Returns the biggest value ever
*/
get: function() {
return this._max;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter2.prototype, "average", {
/**
* Returns the average value since the performance counter is running
*/
get: function() {
return this._average;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter2.prototype, "lastSecAverage", {
/**
* Returns the average value of the last second the counter was monitored
*/
get: function() {
return this._lastSecAverage;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter2.prototype, "current", {
/**
* Returns the current value
*/
get: function() {
return this._current;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter2.prototype, "total", {
/**
* Gets the accumulated total
*/
get: function() {
return this._totalAccumulated;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerfCounter2.prototype, "count", {
/**
* Gets the total value count
*/
get: function() {
return this._totalValueCount;
},
enumerable: true,
configurable: true
});
PerfCounter2.prototype.fetchNewFrame = function() {
this._totalValueCount++;
this._current = 0;
this._lastSecValueCount++;
};
PerfCounter2.prototype.addCount = function(newCount, fetchResult) {
if (!PerfCounter2.Enabled) {
return;
}
this._current += newCount;
if (fetchResult) {
this._fetchResult();
}
};
PerfCounter2.prototype.beginMonitoring = function() {
if (!PerfCounter2.Enabled) {
return;
}
this._startMonitoringTime = Tools.Now;
};
PerfCounter2.prototype.endMonitoring = function(newFrame) {
if (newFrame === void 0) {
newFrame = true;
}
if (!PerfCounter2.Enabled) {
return;
}
if (newFrame) {
this.fetchNewFrame();
}
var currentTime = Tools.Now;
this._current = currentTime - this._startMonitoringTime;
if (newFrame) {
this._fetchResult();
}
};
PerfCounter2.prototype._fetchResult = function() {
this._totalAccumulated += this._current;
this._lastSecAccumulated += this._current;
this._min = Math.min(this._min, this._current);
this._max = Math.max(this._max, this._current);
this._average = this._totalAccumulated / this._totalValueCount;
var now2 = Tools.Now;
if (now2 - this._lastSecTime > 1e3) {
this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
this._lastSecTime = now2;
this._lastSecAccumulated = 0;
this._lastSecValueCount = 0;
}
};
PerfCounter2.Enabled = true;
return PerfCounter2;
}()
);
BABYLON2.PerfCounter = PerfCounter;
function className(name, module) {
return function(target) {
target["__bjsclassName__"] = name;
target["__bjsmoduleName__"] = module != null ? module : null;
};
}
BABYLON2.className = className;
var AsyncLoop = (
/** @class */
function() {
function AsyncLoop2(iterations, func, successCallback2, offset) {
if (offset === void 0) {
offset = 0;
}
this.iterations = iterations;
this.index = offset - 1;
this._done = false;
this._fn = func;
this._successCallback = successCallback2;
}
AsyncLoop2.prototype.executeNext = function() {
if (!this._done) {
if (this.index + 1 < this.iterations) {
++this.index;
this._fn(this);
} else {
this.breakLoop();
}
}
};
AsyncLoop2.prototype.breakLoop = function() {
this._done = true;
this._successCallback();
};
AsyncLoop2.Run = function(iterations, fn, successCallback2, offset) {
if (offset === void 0) {
offset = 0;
}
var loop = new AsyncLoop2(iterations, fn, successCallback2, offset);
loop.executeNext();
return loop;
};
AsyncLoop2.SyncAsyncForLoop = function(iterations, syncedIterations, fn, callback, breakFunction, timeout2) {
if (timeout2 === void 0) {
timeout2 = 0;
}
return AsyncLoop2.Run(Math.ceil(iterations / syncedIterations), function(loop) {
if (breakFunction && breakFunction()) {
loop.breakLoop();
} else {
setTimeout(function() {
for (var i2 = 0; i2 < syncedIterations; ++i2) {
var iteration = loop.index * syncedIterations + i2;
if (iteration >= iterations) {
break;
}
fn(iteration);
if (breakFunction && breakFunction()) {
loop.breakLoop();
break;
}
}
loop.executeNext();
}, timeout2);
}
}, callback);
};
return AsyncLoop2;
}()
);
BABYLON2.AsyncLoop = AsyncLoop;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PromiseStates;
(function(PromiseStates2) {
PromiseStates2[PromiseStates2["Pending"] = 0] = "Pending";
PromiseStates2[PromiseStates2["Fulfilled"] = 1] = "Fulfilled";
PromiseStates2[PromiseStates2["Rejected"] = 2] = "Rejected";
})(PromiseStates || (PromiseStates = {}));
var FulFillmentAgregator = (
/** @class */
function() {
function FulFillmentAgregator2() {
this.count = 0;
this.target = 0;
this.results = [];
}
return FulFillmentAgregator2;
}()
);
var InternalPromise = (
/** @class */
function() {
function InternalPromise2(resolver) {
var _this = this;
this._state = PromiseStates.Pending;
this._children = new Array();
this._rejectWasConsumed = false;
if (!resolver) {
return;
}
try {
resolver(function(value) {
_this._resolve(value);
}, function(reason) {
_this._reject(reason);
});
} catch (e2) {
this._reject(e2);
}
}
Object.defineProperty(InternalPromise2.prototype, "_result", {
get: function() {
return this._resultValue;
},
set: function(value) {
this._resultValue = value;
if (this._parent && this._parent._result === void 0) {
this._parent._result = value;
}
},
enumerable: true,
configurable: true
});
InternalPromise2.prototype.catch = function(onRejected) {
return this.then(void 0, onRejected);
};
InternalPromise2.prototype.then = function(onFulfilled, onRejected) {
var _this = this;
var newPromise = new InternalPromise2();
newPromise._onFulfilled = onFulfilled;
newPromise._onRejected = onRejected;
this._children.push(newPromise);
newPromise._parent = this;
if (this._state !== PromiseStates.Pending) {
BABYLON2.Tools.SetImmediate(function() {
if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
var returnedValue = newPromise._resolve(_this._result);
if (returnedValue !== void 0 && returnedValue !== null) {
if (returnedValue._state !== void 0) {
var returnedPromise = returnedValue;
newPromise._children.push(returnedPromise);
returnedPromise._parent = newPromise;
newPromise = returnedPromise;
} else {
newPromise._result = returnedValue;
}
}
} else {
newPromise._reject(_this._reason);
}
});
}
return newPromise;
};
InternalPromise2.prototype._moveChildren = function(children) {
var _this = this;
var _a;
(_a = this._children).push.apply(_a, children.splice(0, children.length));
this._children.forEach(function(child2) {
child2._parent = _this;
});
if (this._state === PromiseStates.Fulfilled) {
for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
var child = _b[_i];
child._resolve(this._result);
}
} else if (this._state === PromiseStates.Rejected) {
for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
var child = _d[_c];
child._reject(this._reason);
}
}
};
InternalPromise2.prototype._resolve = function(value) {
try {
this._state = PromiseStates.Fulfilled;
var returnedValue = null;
if (this._onFulfilled) {
returnedValue = this._onFulfilled(value);
}
if (returnedValue !== void 0 && returnedValue !== null) {
if (returnedValue._state !== void 0) {
var returnedPromise = returnedValue;
returnedPromise._parent = this;
returnedPromise._moveChildren(this._children);
value = returnedPromise._result;
} else {
value = returnedValue;
}
}
this._result = value;
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
child._resolve(value);
}
this._children.length = 0;
delete this._onFulfilled;
delete this._onRejected;
} catch (e2) {
this._reject(e2, true);
}
};
InternalPromise2.prototype._reject = function(reason, onLocalThrow) {
if (onLocalThrow === void 0) {
onLocalThrow = false;
}
this._state = PromiseStates.Rejected;
this._reason = reason;
if (this._onRejected && !onLocalThrow) {
try {
this._onRejected(reason);
this._rejectWasConsumed = true;
} catch (e2) {
reason = e2;
}
}
for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
var child = _a[_i];
if (this._rejectWasConsumed) {
child._resolve(null);
} else {
child._reject(reason);
}
}
this._children.length = 0;
delete this._onFulfilled;
delete this._onRejected;
};
InternalPromise2.resolve = function(value) {
var newPromise = new InternalPromise2();
newPromise._resolve(value);
return newPromise;
};
InternalPromise2._RegisterForFulfillment = function(promise, agregator, index) {
promise.then(function(value) {
agregator.results[index] = value;
agregator.count++;
if (agregator.count === agregator.target) {
agregator.rootPromise._resolve(agregator.results);
}
return null;
}, function(reason) {
if (agregator.rootPromise._state !== PromiseStates.Rejected) {
agregator.rootPromise._reject(reason);
}
});
};
InternalPromise2.all = function(promises) {
var newPromise = new InternalPromise2();
var agregator = new FulFillmentAgregator();
agregator.target = promises.length;
agregator.rootPromise = newPromise;
if (promises.length) {
for (var index = 0; index < promises.length; index++) {
InternalPromise2._RegisterForFulfillment(promises[index], agregator, index);
}
} else {
newPromise._resolve([]);
}
return newPromise;
};
InternalPromise2.race = function(promises) {
var newPromise = new InternalPromise2();
if (promises.length) {
for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
var promise = promises_1[_i];
promise.then(function(value) {
if (newPromise) {
newPromise._resolve(value);
newPromise = null;
}
return null;
}, function(reason) {
if (newPromise) {
newPromise._reject(reason);
newPromise = null;
}
});
}
}
return newPromise;
};
return InternalPromise2;
}()
);
var PromisePolyfill = (
/** @class */
function() {
function PromisePolyfill2() {
}
PromisePolyfill2.Apply = function(force) {
if (force === void 0) {
force = false;
}
if (force || typeof Promise === "undefined") {
var root = window;
root.Promise = InternalPromise;
}
};
return PromisePolyfill2;
}()
);
BABYLON2.PromisePolyfill = PromisePolyfill;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var WorkerPool = (
/** @class */
function() {
function WorkerPool2(workers) {
this._pendingActions = new Array();
this._workerInfos = workers.map(function(worker) {
return {
worker,
active: false
};
});
}
WorkerPool2.prototype.dispose = function() {
for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
var workerInfo = _a[_i];
workerInfo.worker.terminate();
}
delete this._workerInfos;
delete this._pendingActions;
};
WorkerPool2.prototype.push = function(action) {
for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
var workerInfo = _a[_i];
if (!workerInfo.active) {
this._execute(workerInfo, action);
return;
}
}
this._pendingActions.push(action);
};
WorkerPool2.prototype._execute = function(workerInfo, action) {
var _this = this;
workerInfo.active = true;
action(workerInfo.worker, function() {
workerInfo.active = false;
var nextAction = _this._pendingActions.shift();
if (nextAction) {
_this._execute(workerInfo, nextAction);
}
});
};
return WorkerPool2;
}()
);
BABYLON2.WorkerPool = WorkerPool;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _AlphaState = (
/** @class */
function() {
function _AlphaState2() {
this._isAlphaBlendDirty = false;
this._isBlendFunctionParametersDirty = false;
this._isBlendEquationParametersDirty = false;
this._isBlendConstantsDirty = false;
this._alphaBlend = false;
this._blendFunctionParameters = new Array(4);
this._blendEquationParameters = new Array(2);
this._blendConstants = new Array(4);
this.reset();
}
Object.defineProperty(_AlphaState2.prototype, "isDirty", {
get: function() {
return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_AlphaState2.prototype, "alphaBlend", {
get: function() {
return this._alphaBlend;
},
set: function(value) {
if (this._alphaBlend === value) {
return;
}
this._alphaBlend = value;
this._isAlphaBlendDirty = true;
},
enumerable: true,
configurable: true
});
_AlphaState2.prototype.setAlphaBlendConstants = function(r, g, b2, a) {
if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b2 && this._blendConstants[3] === a) {
return;
}
this._blendConstants[0] = r;
this._blendConstants[1] = g;
this._blendConstants[2] = b2;
this._blendConstants[3] = a;
this._isBlendConstantsDirty = true;
};
_AlphaState2.prototype.setAlphaBlendFunctionParameters = function(value0, value1, value2, value3) {
if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
return;
}
this._blendFunctionParameters[0] = value0;
this._blendFunctionParameters[1] = value1;
this._blendFunctionParameters[2] = value2;
this._blendFunctionParameters[3] = value3;
this._isBlendFunctionParametersDirty = true;
};
_AlphaState2.prototype.setAlphaEquationParameters = function(rgb, alpha) {
if (this._blendEquationParameters[0] === rgb && this._blendEquationParameters[1] === alpha) {
return;
}
this._blendEquationParameters[0] = rgb;
this._blendEquationParameters[1] = alpha;
this._isBlendEquationParametersDirty = true;
};
_AlphaState2.prototype.reset = function() {
this._alphaBlend = false;
this._blendFunctionParameters[0] = null;
this._blendFunctionParameters[1] = null;
this._blendFunctionParameters[2] = null;
this._blendFunctionParameters[3] = null;
this._blendEquationParameters[0] = null;
this._blendEquationParameters[1] = null;
this._blendConstants[0] = null;
this._blendConstants[1] = null;
this._blendConstants[2] = null;
this._blendConstants[3] = null;
this._isAlphaBlendDirty = true;
this._isBlendFunctionParametersDirty = false;
this._isBlendEquationParametersDirty = false;
this._isBlendConstantsDirty = false;
};
_AlphaState2.prototype.apply = function(gl) {
if (!this.isDirty) {
return;
}
if (this._isAlphaBlendDirty) {
if (this._alphaBlend) {
gl.enable(gl.BLEND);
} else {
gl.disable(gl.BLEND);
}
this._isAlphaBlendDirty = false;
}
if (this._isBlendFunctionParametersDirty) {
gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
this._isBlendFunctionParametersDirty = false;
}
if (this._isBlendEquationParametersDirty) {
gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
this._isBlendEquationParametersDirty = false;
}
if (this._isBlendConstantsDirty) {
gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
this._isBlendConstantsDirty = false;
}
};
return _AlphaState2;
}()
);
BABYLON2._AlphaState = _AlphaState;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _DepthCullingState = (
/** @class */
function() {
function _DepthCullingState2() {
this._isDepthTestDirty = false;
this._isDepthMaskDirty = false;
this._isDepthFuncDirty = false;
this._isCullFaceDirty = false;
this._isCullDirty = false;
this._isZOffsetDirty = false;
this._isFrontFaceDirty = false;
this.reset();
}
Object.defineProperty(_DepthCullingState2.prototype, "isDirty", {
get: function() {
return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState2.prototype, "zOffset", {
get: function() {
return this._zOffset;
},
set: function(value) {
if (this._zOffset === value) {
return;
}
this._zOffset = value;
this._isZOffsetDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState2.prototype, "cullFace", {
get: function() {
return this._cullFace;
},
set: function(value) {
if (this._cullFace === value) {
return;
}
this._cullFace = value;
this._isCullFaceDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState2.prototype, "cull", {
get: function() {
return this._cull;
},
set: function(value) {
if (this._cull === value) {
return;
}
this._cull = value;
this._isCullDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState2.prototype, "depthFunc", {
get: function() {
return this._depthFunc;
},
set: function(value) {
if (this._depthFunc === value) {
return;
}
this._depthFunc = value;
this._isDepthFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState2.prototype, "depthMask", {
get: function() {
return this._depthMask;
},
set: function(value) {
if (this._depthMask === value) {
return;
}
this._depthMask = value;
this._isDepthMaskDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState2.prototype, "depthTest", {
get: function() {
return this._depthTest;
},
set: function(value) {
if (this._depthTest === value) {
return;
}
this._depthTest = value;
this._isDepthTestDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_DepthCullingState2.prototype, "frontFace", {
get: function() {
return this._frontFace;
},
set: function(value) {
if (this._frontFace === value) {
return;
}
this._frontFace = value;
this._isFrontFaceDirty = true;
},
enumerable: true,
configurable: true
});
_DepthCullingState2.prototype.reset = function() {
this._depthMask = true;
this._depthTest = true;
this._depthFunc = null;
this._cullFace = null;
this._cull = null;
this._zOffset = 0;
this._frontFace = null;
this._isDepthTestDirty = true;
this._isDepthMaskDirty = true;
this._isDepthFuncDirty = false;
this._isCullFaceDirty = false;
this._isCullDirty = false;
this._isZOffsetDirty = false;
this._isFrontFaceDirty = false;
};
_DepthCullingState2.prototype.apply = function(gl) {
if (!this.isDirty) {
return;
}
if (this._isCullDirty) {
if (this.cull) {
gl.enable(gl.CULL_FACE);
} else {
gl.disable(gl.CULL_FACE);
}
this._isCullDirty = false;
}
if (this._isCullFaceDirty) {
gl.cullFace(this.cullFace);
this._isCullFaceDirty = false;
}
if (this._isDepthMaskDirty) {
gl.depthMask(this.depthMask);
this._isDepthMaskDirty = false;
}
if (this._isDepthTestDirty) {
if (this.depthTest) {
gl.enable(gl.DEPTH_TEST);
} else {
gl.disable(gl.DEPTH_TEST);
}
this._isDepthTestDirty = false;
}
if (this._isDepthFuncDirty) {
gl.depthFunc(this.depthFunc);
this._isDepthFuncDirty = false;
}
if (this._isZOffsetDirty) {
if (this.zOffset) {
gl.enable(gl.POLYGON_OFFSET_FILL);
gl.polygonOffset(this.zOffset, 0);
} else {
gl.disable(gl.POLYGON_OFFSET_FILL);
}
this._isZOffsetDirty = false;
}
if (this._isFrontFaceDirty) {
gl.frontFace(this.frontFace);
this._isFrontFaceDirty = false;
}
};
return _DepthCullingState2;
}()
);
BABYLON2._DepthCullingState = _DepthCullingState;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _StencilState = (
/** @class */
function() {
function _StencilState2() {
this._isStencilTestDirty = false;
this._isStencilMaskDirty = false;
this._isStencilFuncDirty = false;
this._isStencilOpDirty = false;
this.reset();
}
Object.defineProperty(_StencilState2.prototype, "isDirty", {
get: function() {
return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilFunc", {
get: function() {
return this._stencilFunc;
},
set: function(value) {
if (this._stencilFunc === value) {
return;
}
this._stencilFunc = value;
this._isStencilFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilFuncRef", {
get: function() {
return this._stencilFuncRef;
},
set: function(value) {
if (this._stencilFuncRef === value) {
return;
}
this._stencilFuncRef = value;
this._isStencilFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilFuncMask", {
get: function() {
return this._stencilFuncMask;
},
set: function(value) {
if (this._stencilFuncMask === value) {
return;
}
this._stencilFuncMask = value;
this._isStencilFuncDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilOpStencilFail", {
get: function() {
return this._stencilOpStencilFail;
},
set: function(value) {
if (this._stencilOpStencilFail === value) {
return;
}
this._stencilOpStencilFail = value;
this._isStencilOpDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilOpDepthFail", {
get: function() {
return this._stencilOpDepthFail;
},
set: function(value) {
if (this._stencilOpDepthFail === value) {
return;
}
this._stencilOpDepthFail = value;
this._isStencilOpDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilOpStencilDepthPass", {
get: function() {
return this._stencilOpStencilDepthPass;
},
set: function(value) {
if (this._stencilOpStencilDepthPass === value) {
return;
}
this._stencilOpStencilDepthPass = value;
this._isStencilOpDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilMask", {
get: function() {
return this._stencilMask;
},
set: function(value) {
if (this._stencilMask === value) {
return;
}
this._stencilMask = value;
this._isStencilMaskDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_StencilState2.prototype, "stencilTest", {
get: function() {
return this._stencilTest;
},
set: function(value) {
if (this._stencilTest === value) {
return;
}
this._stencilTest = value;
this._isStencilTestDirty = true;
},
enumerable: true,
configurable: true
});
_StencilState2.prototype.reset = function() {
this._stencilTest = false;
this._stencilMask = 255;
this._stencilFunc = BABYLON2.Engine.ALWAYS;
this._stencilFuncRef = 1;
this._stencilFuncMask = 255;
this._stencilOpStencilFail = BABYLON2.Engine.KEEP;
this._stencilOpDepthFail = BABYLON2.Engine.KEEP;
this._stencilOpStencilDepthPass = BABYLON2.Engine.REPLACE;
this._isStencilTestDirty = true;
this._isStencilMaskDirty = true;
this._isStencilFuncDirty = true;
this._isStencilOpDirty = true;
};
_StencilState2.prototype.apply = function(gl) {
if (!this.isDirty) {
return;
}
if (this._isStencilTestDirty) {
if (this.stencilTest) {
gl.enable(gl.STENCIL_TEST);
} else {
gl.disable(gl.STENCIL_TEST);
}
this._isStencilTestDirty = false;
}
if (this._isStencilMaskDirty) {
gl.stencilMask(this.stencilMask);
this._isStencilMaskDirty = false;
}
if (this._isStencilFuncDirty) {
gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
this._isStencilFuncDirty = false;
}
if (this._isStencilOpDirty) {
gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
this._isStencilOpDirty = false;
}
};
return _StencilState2;
}()
);
BABYLON2._StencilState = _StencilState;
})(BABYLON || (BABYLON = {}));
var __assign = function() {
__assign = Object.assign || function(t) {
for (var s, i2 = 1, n = arguments.length; i2 < n; i2++) {
s = arguments[i2];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var BABYLON;
(function(BABYLON2) {
var BufferPointer = (
/** @class */
function() {
function BufferPointer2() {
}
return BufferPointer2;
}()
);
var InstancingAttributeInfo = (
/** @class */
function() {
function InstancingAttributeInfo2() {
}
return InstancingAttributeInfo2;
}()
);
BABYLON2.InstancingAttributeInfo = InstancingAttributeInfo;
var RenderTargetCreationOptions = (
/** @class */
function() {
function RenderTargetCreationOptions2() {
}
return RenderTargetCreationOptions2;
}()
);
BABYLON2.RenderTargetCreationOptions = RenderTargetCreationOptions;
var DepthTextureCreationOptions = (
/** @class */
function() {
function DepthTextureCreationOptions2() {
}
return DepthTextureCreationOptions2;
}()
);
BABYLON2.DepthTextureCreationOptions = DepthTextureCreationOptions;
var EngineCapabilities = (
/** @class */
function() {
function EngineCapabilities2() {
}
return EngineCapabilities2;
}()
);
BABYLON2.EngineCapabilities = EngineCapabilities;
var Engine = (
/** @class */
function() {
function Engine2(canvasOrContext, antialias, options, adaptToDeviceRatio) {
if (adaptToDeviceRatio === void 0) {
adaptToDeviceRatio = false;
}
var _this = this;
this.forcePOTTextures = false;
this.isFullscreen = false;
this.isPointerLock = false;
this.cullBackFaces = true;
this.renderEvenInBackground = true;
this.preventCacheWipeBetweenFrames = false;
this.enableOfflineSupport = false;
this.disableManifestCheck = false;
this.scenes = new Array();
this.postProcesses = new Array();
this.validateShaderPrograms = false;
this.onResizeObservable = new BABYLON2.Observable();
this.onCanvasBlurObservable = new BABYLON2.Observable();
this.onCanvasFocusObservable = new BABYLON2.Observable();
this.onCanvasPointerOutObservable = new BABYLON2.Observable();
this.onBeforeTextureInitObservable = new BABYLON2.Observable();
this._vrDisplay = void 0;
this._vrSupported = false;
this._vrExclusivePointerMode = false;
this.disableUniformBuffers = false;
this._uniformBuffers = new Array();
this.onBeginFrameObservable = new BABYLON2.Observable();
this.onEndFrameObservable = new BABYLON2.Observable();
this.onBeforeShaderCompilationObservable = new BABYLON2.Observable();
this.onAfterShaderCompilationObservable = new BABYLON2.Observable();
this._windowIsBackground = false;
this._webGLVersion = 1;
this._badOS = false;
this._badDesktopOS = false;
this.disableTextureBindingOptimization = false;
this.onVRDisplayChangedObservable = new BABYLON2.Observable();
this.onVRRequestPresentComplete = new BABYLON2.Observable();
this.onVRRequestPresentStart = new BABYLON2.Observable();
this._colorWrite = true;
this._drawCalls = new BABYLON2.PerfCounter();
this._textureCollisions = new BABYLON2.PerfCounter();
this._renderingQueueLaunched = false;
this._activeRenderLoops = new Array();
this._deterministicLockstep = false;
this._lockstepMaxSteps = 4;
this.onContextLostObservable = new BABYLON2.Observable();
this.onContextRestoredObservable = new BABYLON2.Observable();
this._contextWasLost = false;
this._doNotHandleContextLost = false;
this._performanceMonitor = new BABYLON2.PerformanceMonitor();
this._fps = 60;
this._deltaTime = 0;
this.disablePerformanceMonitorInBackground = false;
this._depthCullingState = new BABYLON2._DepthCullingState();
this._stencilState = new BABYLON2._StencilState();
this._alphaState = new BABYLON2._AlphaState();
this._alphaMode = Engine2.ALPHA_DISABLE;
this._internalTexturesCache = new Array();
this._activeChannel = 0;
this._currentTextureChannel = -1;
this._boundTexturesCache = {};
this._compiledEffects = {};
this._vertexAttribArraysEnabled = [];
this._uintIndicesCurrentlySet = false;
this._currentBoundBuffer = new Array();
this._currentFramebuffer = null;
this._currentBufferPointers = new Array();
this._currentInstanceLocations = new Array();
this._currentInstanceBuffers = new Array();
this._firstBoundInternalTextureTracker = new BABYLON2.DummyInternalTextureTracker();
this._lastBoundInternalTextureTracker = new BABYLON2.DummyInternalTextureTracker();
this._vaoRecordInProgress = false;
this._mustWipeVertexAttributes = false;
this._nextFreeTextureSlots = new Array();
this._maxSimultaneousTextures = 0;
this._activeRequests = new Array();
this._texturesSupported = new Array();
this.premultipliedAlpha = true;
this._viewportCached = new BABYLON2.Vector4(0, 0, 0, 0);
this._onVRFullScreenTriggered = function() {
if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
_this._oldSize = new BABYLON2.Size(_this.getRenderWidth(), _this.getRenderHeight());
_this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
var leftEye = _this._vrDisplay.getEyeParameters("left");
_this.setHardwareScalingLevel(1);
_this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
} else {
_this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
_this.setSize(_this._oldSize.width, _this._oldSize.height);
}
};
this._unpackFlipYCached = null;
this.enableUnpackFlipYCached = true;
this._boundUniforms = {};
BABYLON2.PromisePolyfill.Apply();
var canvas2 = null;
Engine2.Instances.push(this);
if (!canvasOrContext) {
return;
}
options = options || {};
if (canvasOrContext.getContext) {
canvas2 = canvasOrContext;
this._renderingCanvas = canvas2;
if (antialias != null) {
options.antialias = antialias;
}
if (options.deterministicLockstep === void 0) {
options.deterministicLockstep = false;
}
if (options.lockstepMaxSteps === void 0) {
options.lockstepMaxSteps = 4;
}
if (options.preserveDrawingBuffer === void 0) {
options.preserveDrawingBuffer = false;
}
if (options.audioEngine === void 0) {
options.audioEngine = true;
}
if (options.stencil === void 0) {
options.stencil = true;
}
if (options.premultipliedAlpha === false) {
this.premultipliedAlpha = false;
}
this._deterministicLockstep = options.deterministicLockstep;
this._lockstepMaxSteps = options.lockstepMaxSteps;
this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
if (navigator && navigator.userAgent) {
var ua = navigator.userAgent;
for (var _i = 0, _a = Engine2.ExceptionList; _i < _a.length; _i++) {
var exception = _a[_i];
var key = exception.key;
var targets = exception.targets;
if (ua.indexOf(key) > -1) {
if (exception.capture && exception.captureConstraint) {
var capture = exception.capture;
var constraint = exception.captureConstraint;
var regex = new RegExp(capture);
var matches = regex.exec(ua);
if (matches && matches.length > 0) {
var capturedValue = parseInt(matches[matches.length - 1]);
if (capturedValue >= constraint) {
continue;
}
}
}
for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
var target = targets_1[_b];
switch (target) {
case "uniformBuffer":
this.disableUniformBuffers = true;
break;
case "textureBindingOptimization":
this.disableTextureBindingOptimization = true;
break;
}
}
}
}
}
if (!options.disableWebGL2Support) {
try {
this._gl = canvas2.getContext("webgl2", options) || canvas2.getContext("experimental-webgl2", options);
if (this._gl) {
this._webGLVersion = 2;
if (!this._gl.deleteQuery) {
this._webGLVersion = 1;
}
}
} catch (e2) {
}
}
if (!this._gl) {
if (!canvas2) {
throw new Error("The provided canvas is null or undefined.");
}
try {
this._gl = canvas2.getContext("webgl", options) || canvas2.getContext("experimental-webgl", options);
} catch (e2) {
throw new Error("WebGL not supported");
}
}
if (!this._gl) {
throw new Error("WebGL not supported");
}
this._onCanvasFocus = function() {
_this.onCanvasFocusObservable.notifyObservers(_this);
};
this._onCanvasBlur = function() {
_this.onCanvasBlurObservable.notifyObservers(_this);
};
canvas2.addEventListener("focus", this._onCanvasFocus);
canvas2.addEventListener("blur", this._onCanvasBlur);
this._onBlur = function() {
if (_this.disablePerformanceMonitorInBackground) {
_this._performanceMonitor.disable();
}
_this._windowIsBackground = true;
};
this._onFocus = function() {
if (_this.disablePerformanceMonitorInBackground) {
_this._performanceMonitor.enable();
}
_this._windowIsBackground = false;
};
this._onCanvasPointerOut = function(ev) {
_this.onCanvasPointerOutObservable.notifyObservers(ev);
};
window.addEventListener("blur", this._onBlur);
window.addEventListener("focus", this._onFocus);
canvas2.addEventListener("pointerout", this._onCanvasPointerOut);
if (!this._doNotHandleContextLost) {
this._onContextLost = function(evt) {
evt.preventDefault();
_this._contextWasLost = true;
BABYLON2.Tools.Warn("WebGL context lost.");
_this.onContextLostObservable.notifyObservers(_this);
};
this._onContextRestored = function(evt) {
setTimeout(function() {
_this._initGLContext();
_this._rebuildEffects();
_this._rebuildInternalTextures();
_this._rebuildBuffers();
_this.wipeCaches(true);
BABYLON2.Tools.Warn("WebGL context successfully restored.");
_this.onContextRestoredObservable.notifyObservers(_this);
_this._contextWasLost = false;
}, 0);
};
canvas2.addEventListener("webglcontextlost", this._onContextLost, false);
canvas2.addEventListener("webglcontextrestored", this._onContextRestored, false);
}
} else {
this._gl = canvasOrContext;
this._renderingCanvas = this._gl.canvas;
if (this._gl.renderbufferStorageMultisample) {
this._webGLVersion = 2;
}
var attributes = this._gl.getContextAttributes();
if (attributes) {
options.stencil = attributes.stencil;
}
}
var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1;
this._hardwareScalingLevel = adaptToDeviceRatio ? 1 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1) : 1;
this.resize();
this._isStencilEnable = options.stencil ? true : false;
this._initGLContext();
if (canvas2) {
this._onFullscreenChange = function() {
if (document.fullscreen !== void 0) {
_this.isFullscreen = document.fullscreen;
} else if (document.mozFullScreen !== void 0) {
_this.isFullscreen = document.mozFullScreen;
} else if (document.webkitIsFullScreen !== void 0) {
_this.isFullscreen = document.webkitIsFullScreen;
} else if (document.msIsFullScreen !== void 0) {
_this.isFullscreen = document.msIsFullScreen;
}
if (_this.isFullscreen && _this._pointerLockRequested && canvas2) {
canvas2.requestPointerLock = canvas2.requestPointerLock || canvas2.msRequestPointerLock || canvas2.mozRequestPointerLock || canvas2.webkitRequestPointerLock;
if (canvas2.requestPointerLock) {
canvas2.requestPointerLock();
}
}
};
document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
this._onPointerLockChange = function() {
_this.isPointerLock = document.mozPointerLockElement === canvas2 || document.webkitPointerLockElement === canvas2 || document.msPointerLockElement === canvas2 || document.pointerLockElement === canvas2;
};
document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
this._onVRDisplayPointerRestricted = function() {
if (canvas2) {
canvas2.requestPointerLock();
}
};
this._onVRDisplayPointerUnrestricted = function() {
document.exitPointerLock();
};
window.addEventListener("vrdisplaypointerrestricted", this._onVRDisplayPointerRestricted, false);
window.addEventListener("vrdisplaypointerunrestricted", this._onVRDisplayPointerUnrestricted, false);
}
if (!Engine2.audioEngine && options.audioEngine && Engine2.AudioEngineFactory) {
Engine2.audioEngine = Engine2.AudioEngineFactory(this.getRenderingCanvas());
}
for (var i2 = 0; i2 < this._caps.maxVertexAttribs; i2++) {
this._currentBufferPointers[i2] = new BufferPointer();
}
this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
if (options.autoEnableWebVR) {
this.initWebVR();
}
this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
console.log("Babylon.js engine (v" + Engine2.Version + ") launched");
this.enableOfflineSupport = BABYLON2.Database !== void 0;
}
Object.defineProperty(Engine2, "LastCreatedEngine", {
/**
* Gets the latest created engine
*/
get: function() {
if (Engine2.Instances.length === 0) {
return null;
}
return Engine2.Instances[Engine2.Instances.length - 1];
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2, "LastCreatedScene", {
/**
* Gets the latest created scene
*/
get: function() {
var lastCreatedEngine = Engine2.LastCreatedEngine;
if (!lastCreatedEngine) {
return null;
}
if (lastCreatedEngine.scenes.length === 0) {
return null;
}
return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
},
enumerable: true,
configurable: true
});
Engine2.MarkAllMaterialsAsDirty = function(flag, predicate) {
for (var engineIndex = 0; engineIndex < Engine2.Instances.length; engineIndex++) {
var engine = Engine2.Instances[engineIndex];
for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
}
}
};
Object.defineProperty(Engine2, "Version", {
/**
* Returns the current version of the framework
*/
get: function() {
return "3.3.0";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "isInVRExclusivePointerMode", {
/**
* Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
* @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
*/
get: function() {
return this._vrExclusivePointerMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "supportsUniformBuffers", {
/**
* Gets a boolean indicating that the engine supports uniform buffers
* @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
*/
get: function() {
return this.webGLVersion > 1 && !this.disableUniformBuffers;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "needPOTTextures", {
/**
* Gets a boolean indicating that only power of 2 textures are supported
* Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
*/
get: function() {
return this._webGLVersion < 2 || this.forcePOTTextures;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "doNotHandleContextLost", {
/**
* Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
* @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
*/
get: function() {
return this._doNotHandleContextLost;
},
set: function(value) {
this._doNotHandleContextLost = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "performanceMonitor", {
/**
* Gets the performance monitor attached to this engine
* @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
*/
get: function() {
return this._performanceMonitor;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "texturesSupported", {
/**
* Gets the list of texture formats supported
*/
get: function() {
return this._texturesSupported;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "textureFormatInUse", {
/**
* Gets the list of texture formats in use
*/
get: function() {
return this._textureFormatInUse;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "currentViewport", {
/**
* Gets the current viewport
*/
get: function() {
return this._cachedViewport;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "emptyTexture", {
/**
* Gets the default empty texture
*/
get: function() {
if (!this._emptyTexture) {
this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine2.TEXTUREFORMAT_RGBA, false, false, Engine2.TEXTURE_NEAREST_SAMPLINGMODE);
}
return this._emptyTexture;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "emptyTexture3D", {
/**
* Gets the default empty 3D texture
*/
get: function() {
if (!this._emptyTexture3D) {
this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine2.TEXTUREFORMAT_RGBA, false, false, Engine2.TEXTURE_NEAREST_SAMPLINGMODE);
}
return this._emptyTexture3D;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "emptyCubeTexture", {
/**
* Gets the default empty cube texture
*/
get: function() {
if (!this._emptyCubeTexture) {
var faceData = new Uint8Array(4);
var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine2.TEXTUREFORMAT_RGBA, Engine2.TEXTURETYPE_UNSIGNED_INT, false, false, Engine2.TEXTURE_NEAREST_SAMPLINGMODE);
}
return this._emptyCubeTexture;
},
enumerable: true,
configurable: true
});
Engine2.prototype._rebuildInternalTextures = function() {
var currentState = this._internalTexturesCache.slice();
for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
var internalTexture = currentState_1[_i];
internalTexture._rebuild();
}
};
Engine2.prototype._rebuildEffects = function() {
for (var key in this._compiledEffects) {
var effect = this._compiledEffects[key];
effect._prepareEffect();
}
BABYLON2.Effect.ResetCache();
};
Engine2.prototype._rebuildBuffers = function() {
for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
var scene = _a[_i];
scene.resetCachedMaterial();
scene._rebuildGeometries();
scene._rebuildTextures();
}
for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
var uniformBuffer = _c[_b];
uniformBuffer._rebuild();
}
};
Engine2.prototype._initGLContext = function() {
this._caps = new EngineCapabilities();
this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
this._glVersion = this._gl.getParameter(this._gl.VERSION);
var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
if (rendererInfo != null) {
this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
}
if (!this._glVendor) {
this._glVendor = "Unknown vendor";
}
if (!this._glRenderer) {
this._glRenderer = "Unknown renderer";
}
this._gl.HALF_FLOAT_OES = 36193;
if (this._gl.RGBA16F !== 34842) {
this._gl.RGBA16F = 34842;
}
if (this._gl.RGBA32F !== 34836) {
this._gl.RGBA32F = 34836;
}
if (this._gl.DEPTH24_STENCIL8 !== 35056) {
this._gl.DEPTH24_STENCIL8 = 35056;
}
this._caps.standardDerivatives = this._webGLVersion > 1 || this._gl.getExtension("OES_standard_derivatives") !== null;
this._caps.astc = this._gl.getExtension("WEBGL_compressed_texture_astc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc");
this._caps.s3tc = this._gl.getExtension("WEBGL_compressed_texture_s3tc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");
this._caps.pvrtc = this._gl.getExtension("WEBGL_compressed_texture_pvrtc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");
this._caps.etc1 = this._gl.getExtension("WEBGL_compressed_texture_etc1") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1");
this._caps.etc2 = this._gl.getExtension("WEBGL_compressed_texture_etc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc") || this._gl.getExtension("WEBGL_compressed_texture_es3_0");
this._caps.textureAnisotropicFilterExtension = this._gl.getExtension("EXT_texture_filter_anisotropic") || this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") || this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic");
this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension("OES_element_index_uint") !== null;
this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension("EXT_frag_depth") !== null;
this._caps.highPrecisionShaderSupported = true;
this._caps.timerQuery = this._gl.getExtension("EXT_disjoint_timer_query_webgl2") || this._gl.getExtension("EXT_disjoint_timer_query");
if (this._caps.timerQuery) {
if (this._webGLVersion === 1) {
this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
}
this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
}
this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float");
this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension("OES_texture_float") ? true : false;
this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension("OES_texture_float_linear") ? true : false;
this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension("OES_texture_half_float") ? true : false;
this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || this._caps.textureHalfFloat && this._gl.getExtension("OES_texture_half_float_linear") ? true : false;
if (this._webGLVersion > 1) {
this._gl.HALF_FLOAT_OES = 5131;
}
this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension("EXT_shader_texture_lod") ? true : false;
if (this._webGLVersion > 1) {
this._caps.drawBuffersExtension = true;
} else {
var drawBuffersExtension = this._gl.getExtension("WEBGL_draw_buffers");
if (drawBuffersExtension !== null) {
this._caps.drawBuffersExtension = true;
this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
for (var i2 = 0; i2 < 16; i2++) {
this._gl["COLOR_ATTACHMENT" + i2 + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i2 + "_WEBGL"];
}
} else {
this._caps.drawBuffersExtension = false;
}
}
if (this._webGLVersion > 1) {
this._caps.depthTextureExtension = true;
} else {
var depthTextureExtension = this._gl.getExtension("WEBGL_depth_texture");
if (depthTextureExtension != null) {
this._caps.depthTextureExtension = true;
this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
}
}
if (this._webGLVersion > 1) {
this._caps.vertexArrayObject = true;
} else {
var vertexArrayObjectExtension = this._gl.getExtension("OES_vertex_array_object");
if (vertexArrayObjectExtension != null) {
this._caps.vertexArrayObject = true;
this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
} else {
this._caps.vertexArrayObject = false;
}
}
if (this._webGLVersion > 1) {
this._caps.instancedArrays = true;
} else {
var instanceExtension = this._gl.getExtension("ANGLE_instanced_arrays");
if (instanceExtension != null) {
this._caps.instancedArrays = true;
this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
} else {
this._caps.instancedArrays = false;
}
}
if (this._caps.astc) {
this.texturesSupported.push("-astc.ktx");
}
if (this._caps.s3tc) {
this.texturesSupported.push("-dxt.ktx");
}
if (this._caps.pvrtc) {
this.texturesSupported.push("-pvrtc.ktx");
}
if (this._caps.etc2) {
this.texturesSupported.push("-etc2.ktx");
}
if (this._caps.etc1) {
this.texturesSupported.push("-etc1.ktx");
}
if (this._gl.getShaderPrecisionFormat) {
var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
if (highp) {
this._caps.highPrecisionShaderSupported = highp.precision !== 0;
}
}
this.setDepthBuffer(true);
this.setDepthFunctionToLessOrEqual();
this.setDepthWrite(true);
this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
this._nextFreeTextureSlots.push(slot);
}
};
Object.defineProperty(Engine2.prototype, "webGLVersion", {
/**
* Gets version of the current webGL context
*/
get: function() {
return this._webGLVersion;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "isStencilEnable", {
/**
* Returns true if the stencil buffer has been enabled through the creation option of the context.
*/
get: function() {
return this._isStencilEnable;
},
enumerable: true,
configurable: true
});
Engine2.prototype._prepareWorkingCanvas = function() {
if (this._workingCanvas) {
return;
}
this._workingCanvas = document.createElement("canvas");
var context = this._workingCanvas.getContext("2d");
if (context) {
this._workingContext = context;
}
};
Engine2.prototype.resetTextureCache = function() {
for (var key in this._boundTexturesCache) {
if (!this._boundTexturesCache.hasOwnProperty(key)) {
continue;
}
var boundTexture = this._boundTexturesCache[key];
if (boundTexture) {
this._removeDesignatedSlot(boundTexture);
}
this._boundTexturesCache[key] = null;
}
if (!this.disableTextureBindingOptimization) {
this._nextFreeTextureSlots = [];
for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
this._nextFreeTextureSlots.push(slot);
}
}
this._currentTextureChannel = -1;
};
Engine2.prototype.isDeterministicLockStep = function() {
return this._deterministicLockstep;
};
Engine2.prototype.getLockstepMaxSteps = function() {
return this._lockstepMaxSteps;
};
Engine2.prototype.getGlInfo = function() {
return {
vendor: this._glVendor,
renderer: this._glRenderer,
version: this._glVersion
};
};
Engine2.prototype.getAspectRatio = function(camera2, useScreen) {
if (useScreen === void 0) {
useScreen = false;
}
var viewport = camera2.viewport;
return this.getRenderWidth(useScreen) * viewport.width / (this.getRenderHeight(useScreen) * viewport.height);
};
Engine2.prototype.getScreenAspectRatio = function() {
return this.getRenderWidth(true) / this.getRenderHeight(true);
};
Engine2.prototype.getRenderWidth = function(useScreen) {
if (useScreen === void 0) {
useScreen = false;
}
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.width;
}
return this._gl.drawingBufferWidth;
};
Engine2.prototype.getRenderHeight = function(useScreen) {
if (useScreen === void 0) {
useScreen = false;
}
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.height;
}
return this._gl.drawingBufferHeight;
};
Engine2.prototype.getRenderingCanvas = function() {
return this._renderingCanvas;
};
Engine2.prototype.getRenderingCanvasClientRect = function() {
if (!this._renderingCanvas) {
return null;
}
return this._renderingCanvas.getBoundingClientRect();
};
Engine2.prototype.setHardwareScalingLevel = function(level) {
this._hardwareScalingLevel = level;
this.resize();
};
Engine2.prototype.getHardwareScalingLevel = function() {
return this._hardwareScalingLevel;
};
Engine2.prototype.getLoadedTexturesCache = function() {
return this._internalTexturesCache;
};
Engine2.prototype.getCaps = function() {
return this._caps;
};
Object.defineProperty(Engine2.prototype, "drawCalls", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
return 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "drawCallsPerfCounter", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Engine2.prototype.getDepthFunction = function() {
return this._depthCullingState.depthFunc;
};
Engine2.prototype.setDepthFunction = function(depthFunc) {
this._depthCullingState.depthFunc = depthFunc;
};
Engine2.prototype.setDepthFunctionToGreater = function() {
this._depthCullingState.depthFunc = this._gl.GREATER;
};
Engine2.prototype.setDepthFunctionToGreaterOrEqual = function() {
this._depthCullingState.depthFunc = this._gl.GEQUAL;
};
Engine2.prototype.setDepthFunctionToLess = function() {
this._depthCullingState.depthFunc = this._gl.LESS;
};
Engine2.prototype.setDepthFunctionToLessOrEqual = function() {
this._depthCullingState.depthFunc = this._gl.LEQUAL;
};
Engine2.prototype.getStencilBuffer = function() {
return this._stencilState.stencilTest;
};
Engine2.prototype.setStencilBuffer = function(enable) {
this._stencilState.stencilTest = enable;
};
Engine2.prototype.getStencilMask = function() {
return this._stencilState.stencilMask;
};
Engine2.prototype.setStencilMask = function(mask) {
this._stencilState.stencilMask = mask;
};
Engine2.prototype.getStencilFunction = function() {
return this._stencilState.stencilFunc;
};
Engine2.prototype.getStencilFunctionReference = function() {
return this._stencilState.stencilFuncRef;
};
Engine2.prototype.getStencilFunctionMask = function() {
return this._stencilState.stencilFuncMask;
};
Engine2.prototype.setStencilFunction = function(stencilFunc) {
this._stencilState.stencilFunc = stencilFunc;
};
Engine2.prototype.setStencilFunctionReference = function(reference) {
this._stencilState.stencilFuncRef = reference;
};
Engine2.prototype.setStencilFunctionMask = function(mask) {
this._stencilState.stencilFuncMask = mask;
};
Engine2.prototype.getStencilOperationFail = function() {
return this._stencilState.stencilOpStencilFail;
};
Engine2.prototype.getStencilOperationDepthFail = function() {
return this._stencilState.stencilOpDepthFail;
};
Engine2.prototype.getStencilOperationPass = function() {
return this._stencilState.stencilOpStencilDepthPass;
};
Engine2.prototype.setStencilOperationFail = function(operation) {
this._stencilState.stencilOpStencilFail = operation;
};
Engine2.prototype.setStencilOperationDepthFail = function(operation) {
this._stencilState.stencilOpDepthFail = operation;
};
Engine2.prototype.setStencilOperationPass = function(operation) {
this._stencilState.stencilOpStencilDepthPass = operation;
};
Engine2.prototype.setDitheringState = function(value) {
if (value) {
this._gl.enable(this._gl.DITHER);
} else {
this._gl.disable(this._gl.DITHER);
}
};
Engine2.prototype.setRasterizerState = function(value) {
if (value) {
this._gl.disable(this._gl.RASTERIZER_DISCARD);
} else {
this._gl.enable(this._gl.RASTERIZER_DISCARD);
}
};
Engine2.prototype.stopRenderLoop = function(renderFunction) {
if (!renderFunction) {
this._activeRenderLoops = [];
return;
}
var index = this._activeRenderLoops.indexOf(renderFunction);
if (index >= 0) {
this._activeRenderLoops.splice(index, 1);
}
};
Engine2.prototype._renderLoop = function() {
if (!this._contextWasLost) {
var shouldRender = true;
if (!this.renderEvenInBackground && this._windowIsBackground) {
shouldRender = false;
}
if (shouldRender) {
this.beginFrame();
for (var index = 0; index < this._activeRenderLoops.length; index++) {
var renderFunction = this._activeRenderLoops[index];
renderFunction();
}
this.endFrame();
}
}
if (this._activeRenderLoops.length > 0) {
var requester = null;
if (this._vrDisplay && this._vrDisplay.isPresenting) {
requester = this._vrDisplay;
}
this._frameHandler = BABYLON2.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
} else {
this._renderingQueueLaunched = false;
}
};
Engine2.prototype.runRenderLoop = function(renderFunction) {
if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
return;
}
this._activeRenderLoops.push(renderFunction);
if (!this._renderingQueueLaunched) {
this._renderingQueueLaunched = true;
this._bindedRenderFunction = this._renderLoop.bind(this);
this._frameHandler = BABYLON2.Tools.QueueNewFrame(this._bindedRenderFunction);
}
};
Engine2.prototype.switchFullscreen = function(requestPointerLock) {
if (this.isFullscreen) {
BABYLON2.Tools.ExitFullscreen();
} else {
this._pointerLockRequested = requestPointerLock;
if (this._renderingCanvas) {
BABYLON2.Tools.RequestFullscreen(this._renderingCanvas);
}
}
};
Engine2.prototype.clear = function(color, backBuffer, depth, stencil) {
if (stencil === void 0) {
stencil = false;
}
this.applyStates();
var mode = 0;
if (backBuffer && color) {
this._gl.clearColor(color.r, color.g, color.b, color.a !== void 0 ? color.a : 1);
mode |= this._gl.COLOR_BUFFER_BIT;
}
if (depth) {
this._gl.clearDepth(1);
mode |= this._gl.DEPTH_BUFFER_BIT;
}
if (stencil) {
this._gl.clearStencil(0);
mode |= this._gl.STENCIL_BUFFER_BIT;
}
this._gl.clear(mode);
};
Engine2.prototype.scissorClear = function(x, y, width, height, clearColor) {
var gl = this._gl;
var curScissor = gl.getParameter(gl.SCISSOR_TEST);
var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
gl.enable(gl.SCISSOR_TEST);
gl.scissor(x, y, width, height);
this.clear(clearColor, true, true, true);
gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
if (curScissor === true) {
gl.enable(gl.SCISSOR_TEST);
} else {
gl.disable(gl.SCISSOR_TEST);
}
};
Engine2.prototype._viewport = function(x, y, width, height) {
if (x !== this._viewportCached.x || y !== this._viewportCached.y || width !== this._viewportCached.z || height !== this._viewportCached.w) {
this._viewportCached.x = x;
this._viewportCached.y = y;
this._viewportCached.z = width;
this._viewportCached.w = height;
this._gl.viewport(x, y, width, height);
}
};
Engine2.prototype.setViewport = function(viewport, requiredWidth, requiredHeight) {
var width = requiredWidth || this.getRenderWidth();
var height = requiredHeight || this.getRenderHeight();
var x = viewport.x || 0;
var y = viewport.y || 0;
this._cachedViewport = viewport;
this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
};
Engine2.prototype.setDirectViewport = function(x, y, width, height) {
var currentViewport = this._cachedViewport;
this._cachedViewport = null;
this._viewport(x, y, width, height);
return currentViewport;
};
Engine2.prototype.beginFrame = function() {
this.onBeginFrameObservable.notifyObservers(this);
this._measureFps();
};
Engine2.prototype.endFrame = function() {
if (this._badOS) {
this.flushFramebuffer();
}
if (this._vrDisplay && this._vrDisplay.isPresenting) {
this._vrDisplay.submitFrame();
}
this.onEndFrameObservable.notifyObservers(this);
};
Engine2.prototype.resize = function() {
if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
}
};
Engine2.prototype.setSize = function(width, height) {
if (!this._renderingCanvas) {
return;
}
if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
return;
}
this._renderingCanvas.width = width;
this._renderingCanvas.height = height;
for (var index = 0; index < this.scenes.length; index++) {
var scene = this.scenes[index];
for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
var cam = scene.cameras[camIndex];
cam._currentRenderId = 0;
}
}
if (this.onResizeObservable.hasObservers) {
this.onResizeObservable.notifyObservers(this);
}
};
Engine2.prototype.isVRDevicePresent = function() {
return !!this._vrDisplay;
};
Engine2.prototype.getVRDevice = function() {
return this._vrDisplay;
};
Engine2.prototype.initWebVR = function() {
this.initWebVRAsync();
return this.onVRDisplayChangedObservable;
};
Engine2.prototype.initWebVRAsync = function() {
var _this = this;
var notifyObservers = function() {
var eventArgs = {
vrDisplay: _this._vrDisplay,
vrSupported: _this._vrSupported
};
_this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
_this._webVRInitPromise = new Promise(function(res) {
res(eventArgs);
});
};
if (!this._onVrDisplayConnect) {
this._onVrDisplayConnect = function(event) {
_this._vrDisplay = event.display;
notifyObservers();
};
this._onVrDisplayDisconnect = function() {
_this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
_this._vrDisplay = void 0;
_this._frameHandler = BABYLON2.Tools.QueueNewFrame(_this._bindedRenderFunction);
notifyObservers();
};
this._onVrDisplayPresentChange = function() {
_this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
};
window.addEventListener("vrdisplayconnect", this._onVrDisplayConnect);
window.addEventListener("vrdisplaydisconnect", this._onVrDisplayDisconnect);
window.addEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange);
}
this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
this._webVRInitPromise.then(notifyObservers);
return this._webVRInitPromise;
};
Engine2.prototype.enableVR = function() {
var _this = this;
if (this._vrDisplay && !this._vrDisplay.isPresenting) {
var onResolved = function() {
_this.onVRRequestPresentComplete.notifyObservers(true);
_this._onVRFullScreenTriggered();
};
var onRejected = function() {
_this.onVRRequestPresentComplete.notifyObservers(false);
};
this.onVRRequestPresentStart.notifyObservers(this);
this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
}
};
Engine2.prototype.disableVR = function() {
if (this._vrDisplay && this._vrDisplay.isPresenting) {
this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
}
};
Engine2.prototype._getVRDisplaysAsync = function() {
var _this = this;
return new Promise(function(res, rej) {
if (navigator.getVRDisplays) {
navigator.getVRDisplays().then(function(devices) {
_this._vrSupported = true;
_this._vrDisplay = devices[0];
res({
vrDisplay: _this._vrDisplay,
vrSupported: _this._vrSupported
});
});
} else {
_this._vrDisplay = void 0;
_this._vrSupported = false;
res({
vrDisplay: _this._vrDisplay,
vrSupported: _this._vrSupported
});
}
});
};
Engine2.prototype.bindFramebuffer = function(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
if (lodLevel === void 0) {
lodLevel = 0;
}
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
}
this._currentRenderTarget = texture;
this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
var gl = this._gl;
if (texture.isCube) {
if (faceIndex === void 0) {
faceIndex = 0;
}
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
if (depthStencilTexture) {
if (depthStencilTexture._generateStencilBuffer) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
} else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
}
}
}
if (this._cachedViewport && !forceFullscreenViewport) {
this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
} else {
if (!requiredWidth) {
requiredWidth = texture.width;
if (lodLevel) {
requiredWidth = requiredWidth / Math.pow(2, lodLevel);
}
}
if (!requiredHeight) {
requiredHeight = texture.height;
if (lodLevel) {
requiredHeight = requiredHeight / Math.pow(2, lodLevel);
}
}
this._viewport(0, 0, requiredWidth, requiredHeight);
}
this.wipeCaches();
};
Engine2.prototype.bindUnboundFramebuffer = function(framebuffer) {
if (this._currentFramebuffer !== framebuffer) {
this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
this._currentFramebuffer = framebuffer;
}
};
Engine2.prototype.unBindFramebuffer = function(texture, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) {
disableGenerateMipMaps = false;
}
this._currentRenderTarget = null;
var gl = this._gl;
if (texture._MSAAFramebuffer) {
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
}
if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
gl.generateMipmap(gl.TEXTURE_2D);
this._bindTextureDirectly(gl.TEXTURE_2D, null);
}
if (onBeforeUnbind) {
if (texture._MSAAFramebuffer) {
this.bindUnboundFramebuffer(texture._framebuffer);
}
onBeforeUnbind();
}
this.bindUnboundFramebuffer(null);
};
Engine2.prototype.unBindMultiColorAttachmentFramebuffer = function(textures, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) {
disableGenerateMipMaps = false;
}
this._currentRenderTarget = null;
var gl = this._gl;
if (textures[0]._MSAAFramebuffer) {
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
var attachments = textures[0]._attachments;
if (!attachments) {
attachments = new Array(textures.length);
textures[0]._attachments = attachments;
}
for (var i2 = 0; i2 < textures.length; i2++) {
var texture = textures[i2];
for (var j = 0; j < attachments.length; j++) {
attachments[j] = gl.NONE;
}
attachments[i2] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i2 : "COLOR_ATTACHMENT" + i2 + "_WEBGL"];
gl.readBuffer(attachments[i2]);
gl.drawBuffers(attachments);
gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
}
for (var i2 = 0; i2 < attachments.length; i2++) {
attachments[i2] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i2 : "COLOR_ATTACHMENT" + i2 + "_WEBGL"];
}
gl.drawBuffers(attachments);
}
for (var i2 = 0; i2 < textures.length; i2++) {
var texture = textures[i2];
if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
this._bindTextureDirectly(gl.TEXTURE_2D, texture);
gl.generateMipmap(gl.TEXTURE_2D);
this._bindTextureDirectly(gl.TEXTURE_2D, null);
}
}
if (onBeforeUnbind) {
if (textures[0]._MSAAFramebuffer) {
this.bindUnboundFramebuffer(textures[0]._framebuffer);
}
onBeforeUnbind();
}
this.bindUnboundFramebuffer(null);
};
Engine2.prototype.generateMipMapsForCubemap = function(texture) {
if (texture.generateMipMaps) {
var gl = this._gl;
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
}
};
Engine2.prototype.flushFramebuffer = function() {
this._gl.flush();
};
Engine2.prototype.restoreDefaultFramebuffer = function() {
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
} else {
this.bindUnboundFramebuffer(null);
}
if (this._cachedViewport) {
this.setViewport(this._cachedViewport);
}
this.wipeCaches();
};
Engine2.prototype.createUniformBuffer = function(elements) {
var ubo = this._gl.createBuffer();
if (!ubo) {
throw new Error("Unable to create uniform buffer");
}
this.bindUniformBuffer(ubo);
if (elements instanceof Float32Array) {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
} else {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
}
this.bindUniformBuffer(null);
ubo.references = 1;
return ubo;
};
Engine2.prototype.createDynamicUniformBuffer = function(elements) {
var ubo = this._gl.createBuffer();
if (!ubo) {
throw new Error("Unable to create dynamic uniform buffer");
}
this.bindUniformBuffer(ubo);
if (elements instanceof Float32Array) {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
} else {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
}
this.bindUniformBuffer(null);
ubo.references = 1;
return ubo;
};
Engine2.prototype.updateUniformBuffer = function(uniformBuffer, elements, offset, count) {
this.bindUniformBuffer(uniformBuffer);
if (offset === void 0) {
offset = 0;
}
if (count === void 0) {
if (elements instanceof Float32Array) {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
} else {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
}
} else {
if (elements instanceof Float32Array) {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
} else {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
}
}
this.bindUniformBuffer(null);
};
Engine2.prototype._resetVertexBufferBinding = function() {
this.bindArrayBuffer(null);
this._cachedVertexBuffers = null;
};
Engine2.prototype.createVertexBuffer = function(data2) {
var vbo = this._gl.createBuffer();
if (!vbo) {
throw new Error("Unable to create vertex buffer");
}
this.bindArrayBuffer(vbo);
if (data2 instanceof Array) {
this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data2), this._gl.STATIC_DRAW);
} else {
this._gl.bufferData(this._gl.ARRAY_BUFFER, data2, this._gl.STATIC_DRAW);
}
this._resetVertexBufferBinding();
vbo.references = 1;
return vbo;
};
Engine2.prototype.createDynamicVertexBuffer = function(data2) {
var vbo = this._gl.createBuffer();
if (!vbo) {
throw new Error("Unable to create dynamic vertex buffer");
}
this.bindArrayBuffer(vbo);
if (data2 instanceof Array) {
this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data2), this._gl.DYNAMIC_DRAW);
} else {
this._gl.bufferData(this._gl.ARRAY_BUFFER, data2, this._gl.DYNAMIC_DRAW);
}
this._resetVertexBufferBinding();
vbo.references = 1;
return vbo;
};
Engine2.prototype.updateDynamicIndexBuffer = function(indexBuffer, indices, offset) {
if (offset === void 0) {
offset = 0;
}
this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
this.bindIndexBuffer(indexBuffer);
var arrayBuffer;
if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
arrayBuffer = indices;
} else {
arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
}
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
this._resetIndexBufferBinding();
};
Engine2.prototype.updateDynamicVertexBuffer = function(vertexBuffer, data2, byteOffset, byteLength) {
this.bindArrayBuffer(vertexBuffer);
if (byteOffset === void 0) {
byteOffset = 0;
}
if (byteLength === void 0) {
if (data2 instanceof Array) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data2));
} else {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data2);
}
} else {
if (data2 instanceof Array) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data2).subarray(byteOffset, byteOffset + byteLength));
} else {
if (data2 instanceof ArrayBuffer) {
data2 = new Uint8Array(data2, byteOffset, byteLength);
} else {
data2 = new Uint8Array(data2.buffer, data2.byteOffset + byteOffset, byteLength);
}
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data2);
}
}
this._resetVertexBufferBinding();
};
Engine2.prototype._resetIndexBufferBinding = function() {
this.bindIndexBuffer(null);
this._cachedIndexBuffer = null;
};
Engine2.prototype.createIndexBuffer = function(indices, updatable) {
var vbo = this._gl.createBuffer();
if (!vbo) {
throw new Error("Unable to create index buffer");
}
this.bindIndexBuffer(vbo);
var arrayBuffer;
var need32Bits = false;
if (indices instanceof Uint16Array) {
arrayBuffer = indices;
} else {
if (this._caps.uintIndices) {
if (indices instanceof Uint32Array) {
arrayBuffer = indices;
need32Bits = true;
} else {
for (var index = 0; index < indices.length; index++) {
if (indices[index] > 65535) {
need32Bits = true;
break;
}
}
arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
}
} else {
arrayBuffer = new Uint16Array(indices);
}
}
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
this._resetIndexBufferBinding();
vbo.references = 1;
vbo.is32Bits = need32Bits;
return vbo;
};
Engine2.prototype.bindArrayBuffer = function(buffer) {
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
};
Engine2.prototype.bindUniformBuffer = function(buffer) {
this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
};
Engine2.prototype.bindUniformBufferBase = function(buffer, location2) {
this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location2, buffer);
};
Engine2.prototype.bindUniformBlock = function(shaderProgram, blockName, index) {
var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
};
Engine2.prototype.bindIndexBuffer = function(buffer) {
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
};
Engine2.prototype.bindBuffer = function(buffer, target) {
if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
this._gl.bindBuffer(target, buffer);
this._currentBoundBuffer[target] = buffer;
}
};
Engine2.prototype.updateArrayBuffer = function(data2) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data2);
};
Engine2.prototype._vertexAttribPointer = function(buffer, indx, size, type, normalized, stride, offset) {
var pointer = this._currentBufferPointers[indx];
var changed = false;
if (!pointer.active) {
changed = true;
pointer.active = true;
pointer.index = indx;
pointer.size = size;
pointer.type = type;
pointer.normalized = normalized;
pointer.stride = stride;
pointer.offset = offset;
pointer.buffer = buffer;
} else {
if (pointer.buffer !== buffer) {
pointer.buffer = buffer;
changed = true;
}
if (pointer.size !== size) {
pointer.size = size;
changed = true;
}
if (pointer.type !== type) {
pointer.type = type;
changed = true;
}
if (pointer.normalized !== normalized) {
pointer.normalized = normalized;
changed = true;
}
if (pointer.stride !== stride) {
pointer.stride = stride;
changed = true;
}
if (pointer.offset !== offset) {
pointer.offset = offset;
changed = true;
}
}
if (changed || this._vaoRecordInProgress) {
this.bindArrayBuffer(buffer);
this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
}
};
Engine2.prototype._bindIndexBufferWithCache = function(indexBuffer) {
if (indexBuffer == null) {
return;
}
if (this._cachedIndexBuffer !== indexBuffer) {
this._cachedIndexBuffer = indexBuffer;
this.bindIndexBuffer(indexBuffer);
this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
}
};
Engine2.prototype._bindVertexBuffersAttributes = function(vertexBuffers, effect) {
var attributes = effect.getAttributesNames();
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.unbindAllAttributes();
for (var index = 0; index < attributes.length; index++) {
var order = effect.getAttributeLocation(index);
if (order >= 0) {
var vertexBuffer = vertexBuffers[attributes[index]];
if (!vertexBuffer) {
continue;
}
this._gl.enableVertexAttribArray(order);
if (!this._vaoRecordInProgress) {
this._vertexAttribArraysEnabled[order] = true;
}
var buffer = vertexBuffer.getBuffer();
if (buffer) {
this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
if (vertexBuffer.getIsInstanced()) {
this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
if (!this._vaoRecordInProgress) {
this._currentInstanceLocations.push(order);
this._currentInstanceBuffers.push(buffer);
}
}
}
}
}
};
Engine2.prototype.recordVertexArrayObject = function(vertexBuffers, indexBuffer, effect) {
var vao = this._gl.createVertexArray();
this._vaoRecordInProgress = true;
this._gl.bindVertexArray(vao);
this._mustWipeVertexAttributes = true;
this._bindVertexBuffersAttributes(vertexBuffers, effect);
this.bindIndexBuffer(indexBuffer);
this._vaoRecordInProgress = false;
this._gl.bindVertexArray(null);
return vao;
};
Engine2.prototype.bindVertexArrayObject = function(vertexArrayObject, indexBuffer) {
if (this._cachedVertexArrayObject !== vertexArrayObject) {
this._cachedVertexArrayObject = vertexArrayObject;
this._gl.bindVertexArray(vertexArrayObject);
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
this._mustWipeVertexAttributes = true;
}
};
Engine2.prototype.bindBuffersDirectly = function(vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
this._cachedVertexBuffers = vertexBuffer;
this._cachedEffectForVertexBuffers = effect;
var attributesCount = effect.getAttributesCount();
this._unbindVertexArrayObject();
this.unbindAllAttributes();
var offset = 0;
for (var index = 0; index < attributesCount; index++) {
if (index < vertexDeclaration.length) {
var order = effect.getAttributeLocation(index);
if (order >= 0) {
this._gl.enableVertexAttribArray(order);
this._vertexAttribArraysEnabled[order] = true;
this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
}
offset += vertexDeclaration[index] * 4;
}
}
}
this._bindIndexBufferWithCache(indexBuffer);
};
Engine2.prototype._unbindVertexArrayObject = function() {
if (!this._cachedVertexArrayObject) {
return;
}
this._cachedVertexArrayObject = null;
this._gl.bindVertexArray(null);
};
Engine2.prototype.bindBuffers = function(vertexBuffers, indexBuffer, effect) {
if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
this._cachedVertexBuffers = vertexBuffers;
this._cachedEffectForVertexBuffers = effect;
this._bindVertexBuffersAttributes(vertexBuffers, effect);
}
this._bindIndexBufferWithCache(indexBuffer);
};
Engine2.prototype.unbindInstanceAttributes = function() {
var boundBuffer;
for (var i2 = 0, ul = this._currentInstanceLocations.length; i2 < ul; i2++) {
var instancesBuffer = this._currentInstanceBuffers[i2];
if (boundBuffer != instancesBuffer && instancesBuffer.references) {
boundBuffer = instancesBuffer;
this.bindArrayBuffer(instancesBuffer);
}
var offsetLocation = this._currentInstanceLocations[i2];
this._gl.vertexAttribDivisor(offsetLocation, 0);
}
this._currentInstanceBuffers.length = 0;
this._currentInstanceLocations.length = 0;
};
Engine2.prototype.releaseVertexArrayObject = function(vao) {
this._gl.deleteVertexArray(vao);
};
Engine2.prototype._releaseBuffer = function(buffer) {
buffer.references--;
if (buffer.references === 0) {
this._gl.deleteBuffer(buffer);
return true;
}
return false;
};
Engine2.prototype.createInstancesBuffer = function(capacity) {
var buffer = this._gl.createBuffer();
if (!buffer) {
throw new Error("Unable to create instance buffer");
}
buffer.capacity = capacity;
this.bindArrayBuffer(buffer);
this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
return buffer;
};
Engine2.prototype.deleteInstancesBuffer = function(buffer) {
this._gl.deleteBuffer(buffer);
};
Engine2.prototype.updateAndBindInstancesBuffer = function(instancesBuffer, data2, offsetLocations) {
this.bindArrayBuffer(instancesBuffer);
if (data2) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data2);
}
if (offsetLocations[0].index !== void 0) {
var stride = 0;
for (var i2 = 0; i2 < offsetLocations.length; i2++) {
var ai = offsetLocations[i2];
stride += ai.attributeSize * 4;
}
for (var i2 = 0; i2 < offsetLocations.length; i2++) {
var ai = offsetLocations[i2];
if (!this._vertexAttribArraysEnabled[ai.index]) {
this._gl.enableVertexAttribArray(ai.index);
this._vertexAttribArraysEnabled[ai.index] = true;
}
this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
this._gl.vertexAttribDivisor(ai.index, 1);
this._currentInstanceLocations.push(ai.index);
this._currentInstanceBuffers.push(instancesBuffer);
}
} else {
for (var index = 0; index < 4; index++) {
var offsetLocation = offsetLocations[index];
if (!this._vertexAttribArraysEnabled[offsetLocation]) {
this._gl.enableVertexAttribArray(offsetLocation);
this._vertexAttribArraysEnabled[offsetLocation] = true;
}
this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
this._gl.vertexAttribDivisor(offsetLocation, 1);
this._currentInstanceLocations.push(offsetLocation);
this._currentInstanceBuffers.push(instancesBuffer);
}
}
};
Engine2.prototype.applyStates = function() {
this._depthCullingState.apply(this._gl);
this._stencilState.apply(this._gl);
this._alphaState.apply(this._gl);
};
Engine2.prototype.draw = function(useTriangles, indexStart, indexCount, instancesCount) {
this.drawElementsType(useTriangles ? BABYLON2.Material.TriangleFillMode : BABYLON2.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
};
Engine2.prototype.drawPointClouds = function(verticesStart, verticesCount, instancesCount) {
this.drawArraysType(BABYLON2.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
};
Engine2.prototype.drawUnIndexed = function(useTriangles, verticesStart, verticesCount, instancesCount) {
this.drawArraysType(useTriangles ? BABYLON2.Material.TriangleFillMode : BABYLON2.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
};
Engine2.prototype.drawElementsType = function(fillMode, indexStart, indexCount, instancesCount) {
this.applyStates();
this._drawCalls.addCount(1, false);
var drawMode = this._drawMode(fillMode);
var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
var mult = this._uintIndicesCurrentlySet ? 4 : 2;
if (instancesCount) {
this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
} else {
this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
}
};
Engine2.prototype.drawArraysType = function(fillMode, verticesStart, verticesCount, instancesCount) {
this.applyStates();
this._drawCalls.addCount(1, false);
var drawMode = this._drawMode(fillMode);
if (instancesCount) {
this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
} else {
this._gl.drawArrays(drawMode, verticesStart, verticesCount);
}
};
Engine2.prototype._drawMode = function(fillMode) {
switch (fillMode) {
case BABYLON2.Material.TriangleFillMode:
return this._gl.TRIANGLES;
case BABYLON2.Material.PointFillMode:
return this._gl.POINTS;
case BABYLON2.Material.WireFrameFillMode:
return this._gl.LINES;
case BABYLON2.Material.PointListDrawMode:
return this._gl.POINTS;
case BABYLON2.Material.LineListDrawMode:
return this._gl.LINES;
case BABYLON2.Material.LineLoopDrawMode:
return this._gl.LINE_LOOP;
case BABYLON2.Material.LineStripDrawMode:
return this._gl.LINE_STRIP;
case BABYLON2.Material.TriangleStripDrawMode:
return this._gl.TRIANGLE_STRIP;
case BABYLON2.Material.TriangleFanDrawMode:
return this._gl.TRIANGLE_FAN;
default:
return this._gl.TRIANGLES;
}
};
Engine2.prototype._releaseEffect = function(effect) {
if (this._compiledEffects[effect._key]) {
delete this._compiledEffects[effect._key];
this._deleteProgram(effect.getProgram());
}
};
Engine2.prototype._deleteProgram = function(program) {
if (program) {
program.__SPECTOR_rebuildProgram = null;
if (program.transformFeedback) {
this.deleteTransformFeedback(program.transformFeedback);
program.transformFeedback = null;
}
this._gl.deleteProgram(program);
}
};
Engine2.prototype.createEffect = function(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
var vertex = baseName.vertexElement || baseName.vertex || baseName;
var fragment = baseName.fragmentElement || baseName.fragment || baseName;
var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
if (this._compiledEffects[name]) {
var compiledEffect = this._compiledEffects[name];
if (onCompiled && compiledEffect.isReady()) {
onCompiled(compiledEffect);
}
return compiledEffect;
}
var effect = new BABYLON2.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
effect._key = name;
this._compiledEffects[name] = effect;
return effect;
};
Engine2.prototype._compileShader = function(source, type, defines, shaderVersion) {
return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
};
Engine2.prototype._compileRawShader = function(source, type) {
var gl = this._gl;
var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
if (!shader) {
throw new Error("Something went wrong while compile the shader.");
}
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var log = gl.getShaderInfoLog(shader);
if (log) {
throw new Error(log);
}
}
return shader;
};
Engine2.prototype.createRawShaderProgram = function(vertexCode, fragmentCode, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) {
transformFeedbackVaryings = null;
}
context = context || this._gl;
var vertexShader = this._compileRawShader(vertexCode, "vertex");
var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
};
Engine2.prototype.createShaderProgram = function(vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) {
transformFeedbackVaryings = null;
}
context = context || this._gl;
this.onBeforeShaderCompilationObservable.notifyObservers(this);
var shaderVersion = this._webGLVersion > 1 ? "#version 300 es\n#define WEBGL2 \n" : "";
var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
this.onAfterShaderCompilationObservable.notifyObservers(this);
return program;
};
Engine2.prototype._createShaderProgram = function(vertexShader, fragmentShader, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) {
transformFeedbackVaryings = null;
}
var shaderProgram = context.createProgram();
if (!shaderProgram) {
throw new Error("Unable to create program");
}
context.attachShader(shaderProgram, vertexShader);
context.attachShader(shaderProgram, fragmentShader);
if (this.webGLVersion > 1 && transformFeedbackVaryings) {
var transformFeedback = this.createTransformFeedback();
this.bindTransformFeedback(transformFeedback);
this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
shaderProgram.transformFeedback = transformFeedback;
}
context.linkProgram(shaderProgram);
if (this.webGLVersion > 1 && transformFeedbackVaryings) {
this.bindTransformFeedback(null);
}
var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
if (!linked) {
var error = context.getProgramInfoLog(shaderProgram);
if (error) {
throw new Error(error);
}
}
if (this.validateShaderPrograms) {
context.validateProgram(shaderProgram);
var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
if (!validated) {
var error = context.getProgramInfoLog(shaderProgram);
if (error) {
throw new Error(error);
}
}
}
context.deleteShader(vertexShader);
context.deleteShader(fragmentShader);
return shaderProgram;
};
Engine2.prototype.getUniforms = function(shaderProgram, uniformsNames) {
var results = new Array();
for (var index = 0; index < uniformsNames.length; index++) {
results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
}
return results;
};
Engine2.prototype.getAttributes = function(shaderProgram, attributesNames) {
var results = [];
for (var index = 0; index < attributesNames.length; index++) {
try {
results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
} catch (e2) {
results.push(-1);
}
}
return results;
};
Engine2.prototype.enableEffect = function(effect) {
if (!effect || effect === this._currentEffect) {
return;
}
this.bindSamplers(effect);
this._currentEffect = effect;
if (effect.onBind) {
effect.onBind(effect);
}
if (effect._onBindObservable) {
effect._onBindObservable.notifyObservers(effect);
}
};
Engine2.prototype.setIntArray = function(uniform, array) {
if (!uniform) {
return;
}
this._gl.uniform1iv(uniform, array);
};
Engine2.prototype.setIntArray2 = function(uniform, array) {
if (!uniform || array.length % 2 !== 0) {
return;
}
this._gl.uniform2iv(uniform, array);
};
Engine2.prototype.setIntArray3 = function(uniform, array) {
if (!uniform || array.length % 3 !== 0) {
return;
}
this._gl.uniform3iv(uniform, array);
};
Engine2.prototype.setIntArray4 = function(uniform, array) {
if (!uniform || array.length % 4 !== 0) {
return;
}
this._gl.uniform4iv(uniform, array);
};
Engine2.prototype.setFloatArray = function(uniform, array) {
if (!uniform) {
return;
}
this._gl.uniform1fv(uniform, array);
};
Engine2.prototype.setFloatArray2 = function(uniform, array) {
if (!uniform || array.length % 2 !== 0) {
return;
}
this._gl.uniform2fv(uniform, array);
};
Engine2.prototype.setFloatArray3 = function(uniform, array) {
if (!uniform || array.length % 3 !== 0) {
return;
}
this._gl.uniform3fv(uniform, array);
};
Engine2.prototype.setFloatArray4 = function(uniform, array) {
if (!uniform || array.length % 4 !== 0) {
return;
}
this._gl.uniform4fv(uniform, array);
};
Engine2.prototype.setArray = function(uniform, array) {
if (!uniform) {
return;
}
this._gl.uniform1fv(uniform, array);
};
Engine2.prototype.setArray2 = function(uniform, array) {
if (!uniform || array.length % 2 !== 0) {
return;
}
this._gl.uniform2fv(uniform, array);
};
Engine2.prototype.setArray3 = function(uniform, array) {
if (!uniform || array.length % 3 !== 0) {
return;
}
this._gl.uniform3fv(uniform, array);
};
Engine2.prototype.setArray4 = function(uniform, array) {
if (!uniform || array.length % 4 !== 0) {
return;
}
this._gl.uniform4fv(uniform, array);
};
Engine2.prototype.setMatrices = function(uniform, matrices) {
if (!uniform) {
return;
}
this._gl.uniformMatrix4fv(uniform, false, matrices);
};
Engine2.prototype.setMatrix = function(uniform, matrix) {
if (!uniform) {
return;
}
this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
};
Engine2.prototype.setMatrix3x3 = function(uniform, matrix) {
if (!uniform) {
return;
}
this._gl.uniformMatrix3fv(uniform, false, matrix);
};
Engine2.prototype.setMatrix2x2 = function(uniform, matrix) {
if (!uniform) {
return;
}
this._gl.uniformMatrix2fv(uniform, false, matrix);
};
Engine2.prototype.setInt = function(uniform, value) {
if (!uniform) {
return;
}
this._gl.uniform1i(uniform, value);
};
Engine2.prototype.setFloat = function(uniform, value) {
if (!uniform) {
return;
}
this._gl.uniform1f(uniform, value);
};
Engine2.prototype.setFloat2 = function(uniform, x, y) {
if (!uniform) {
return;
}
this._gl.uniform2f(uniform, x, y);
};
Engine2.prototype.setFloat3 = function(uniform, x, y, z) {
if (!uniform) {
return;
}
this._gl.uniform3f(uniform, x, y, z);
};
Engine2.prototype.setBool = function(uniform, bool) {
if (!uniform) {
return;
}
this._gl.uniform1i(uniform, bool);
};
Engine2.prototype.setFloat4 = function(uniform, x, y, z, w) {
if (!uniform) {
return;
}
this._gl.uniform4f(uniform, x, y, z, w);
};
Engine2.prototype.setColor3 = function(uniform, color3) {
if (!uniform) {
return;
}
this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
};
Engine2.prototype.setColor4 = function(uniform, color3, alpha) {
if (!uniform) {
return;
}
this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
};
Engine2.prototype.setDirectColor4 = function(uniform, color4) {
if (!uniform) {
return;
}
this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
};
Engine2.prototype.setState = function(culling, zOffset, force, reverseSide) {
if (zOffset === void 0) {
zOffset = 0;
}
if (reverseSide === void 0) {
reverseSide = false;
}
if (this._depthCullingState.cull !== culling || force) {
this._depthCullingState.cull = culling;
}
var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
if (this._depthCullingState.cullFace !== cullFace || force) {
this._depthCullingState.cullFace = cullFace;
}
this.setZOffset(zOffset);
var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
if (this._depthCullingState.frontFace !== frontFace || force) {
this._depthCullingState.frontFace = frontFace;
}
};
Engine2.prototype.setZOffset = function(value) {
this._depthCullingState.zOffset = value;
};
Engine2.prototype.getZOffset = function() {
return this._depthCullingState.zOffset;
};
Engine2.prototype.setDepthBuffer = function(enable) {
this._depthCullingState.depthTest = enable;
};
Engine2.prototype.getDepthWrite = function() {
return this._depthCullingState.depthMask;
};
Engine2.prototype.setDepthWrite = function(enable) {
this._depthCullingState.depthMask = enable;
};
Engine2.prototype.setColorWrite = function(enable) {
this._gl.colorMask(enable, enable, enable, enable);
this._colorWrite = enable;
};
Engine2.prototype.getColorWrite = function() {
return this._colorWrite;
};
Engine2.prototype.setAlphaConstants = function(r, g, b2, a) {
this._alphaState.setAlphaBlendConstants(r, g, b2, a);
};
Engine2.prototype.setAlphaMode = function(mode, noDepthWriteChange) {
if (noDepthWriteChange === void 0) {
noDepthWriteChange = false;
}
if (this._alphaMode === mode) {
return;
}
switch (mode) {
case Engine2.ALPHA_DISABLE:
this._alphaState.alphaBlend = false;
break;
case Engine2.ALPHA_PREMULTIPLIED:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_PREMULTIPLIED_PORTERDUFF:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_COMBINE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_ONEONE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_ADD:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_SUBTRACT:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_MULTIPLY:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_MAXIMIZED:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_INTERPOLATE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
this._alphaState.alphaBlend = true;
break;
case Engine2.ALPHA_SCREENMODE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
}
if (!noDepthWriteChange) {
this.setDepthWrite(mode === Engine2.ALPHA_DISABLE);
}
this._alphaMode = mode;
};
Engine2.prototype.getAlphaMode = function() {
return this._alphaMode;
};
Engine2.prototype.clearInternalTexturesCache = function() {
this._internalTexturesCache = [];
};
Engine2.prototype.wipeCaches = function(bruteForce) {
if (this.preventCacheWipeBetweenFrames && !bruteForce) {
return;
}
this._currentEffect = null;
this._viewportCached.x = 0;
this._viewportCached.y = 0;
this._viewportCached.z = 0;
this._viewportCached.w = 0;
if (bruteForce) {
this.resetTextureCache();
this._currentProgram = null;
this._stencilState.reset();
this._depthCullingState.reset();
this.setDepthFunctionToLessOrEqual();
this._alphaState.reset();
this._unpackFlipYCached = null;
}
this._resetVertexBufferBinding();
this._cachedIndexBuffer = null;
this._cachedEffectForVertexBuffers = null;
this._unbindVertexArrayObject();
this.bindIndexBuffer(null);
};
Engine2.prototype.setTextureFormatToUse = function(formatsAvailable) {
for (var i2 = 0, len1 = this.texturesSupported.length; i2 < len1; i2++) {
for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
if (this._texturesSupported[i2] === formatsAvailable[j].toLowerCase()) {
return this._textureFormatInUse = this._texturesSupported[i2];
}
}
}
this._textureFormatInUse = null;
return null;
};
Engine2.prototype._getSamplingParameters = function(samplingMode, generateMipMaps) {
var gl = this._gl;
var magFilter = gl.NEAREST;
var minFilter = gl.NEAREST;
switch (samplingMode) {
case Engine2.TEXTURE_BILINEAR_SAMPLINGMODE:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_NEAREST;
} else {
minFilter = gl.LINEAR;
}
break;
case Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_LINEAR;
} else {
minFilter = gl.LINEAR;
}
break;
case Engine2.TEXTURE_NEAREST_SAMPLINGMODE:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_LINEAR;
} else {
minFilter = gl.NEAREST;
}
break;
case Engine2.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_NEAREST;
} else {
minFilter = gl.NEAREST;
}
break;
case Engine2.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_NEAREST;
} else {
minFilter = gl.LINEAR;
}
break;
case Engine2.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_LINEAR;
} else {
minFilter = gl.LINEAR;
}
break;
case Engine2.TEXTURE_NEAREST_LINEAR:
magFilter = gl.NEAREST;
minFilter = gl.LINEAR;
break;
case Engine2.TEXTURE_NEAREST_NEAREST:
magFilter = gl.NEAREST;
minFilter = gl.NEAREST;
break;
case Engine2.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_NEAREST;
} else {
minFilter = gl.NEAREST;
}
break;
case Engine2.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_LINEAR;
} else {
minFilter = gl.NEAREST;
}
break;
case Engine2.TEXTURE_LINEAR_LINEAR:
magFilter = gl.LINEAR;
minFilter = gl.LINEAR;
break;
case Engine2.TEXTURE_LINEAR_NEAREST:
magFilter = gl.LINEAR;
minFilter = gl.NEAREST;
break;
}
return {
min: minFilter,
mag: magFilter
};
};
Engine2.prototype._partialLoadImg = function(url, index, loadedImages, scene, onfinish, onErrorCallBack) {
if (onErrorCallBack === void 0) {
onErrorCallBack = null;
}
var img;
var onload = function() {
loadedImages[index] = img;
loadedImages._internalCount++;
if (scene) {
scene._removePendingData(img);
}
if (loadedImages._internalCount === 6) {
onfinish(loadedImages);
}
};
var onerror = function(message, exception) {
if (scene) {
scene._removePendingData(img);
}
if (onErrorCallBack) {
onErrorCallBack(message, exception);
}
};
img = BABYLON2.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
if (scene) {
scene._addPendingData(img);
}
};
Engine2.prototype._cascadeLoadImgs = function(rootUrl, scene, onfinish, files, onError) {
if (onError === void 0) {
onError = null;
}
var loadedImages = [];
loadedImages._internalCount = 0;
for (var index = 0; index < 6; index++) {
this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
}
};
Engine2.prototype._createTexture = function() {
var texture = this._gl.createTexture();
if (!texture) {
throw new Error("Unable to create texture");
}
return texture;
};
Engine2.prototype.createTexture = function(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
var _this = this;
if (samplingMode === void 0) {
samplingMode = Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE;
}
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (buffer === void 0) {
buffer = null;
}
if (fallback === void 0) {
fallback = null;
}
if (format === void 0) {
format = null;
}
if (forcedExtension === void 0) {
forcedExtension = null;
}
var url = String(urlArg);
var fromData = url.substr(0, 5) === "data:";
var fromBlob = url.substr(0, 5) === "blob:";
var isBase64 = fromData && url.indexOf(";base64,") !== -1;
var texture = fallback ? fallback : new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_URL);
var lastDot = url.lastIndexOf(".");
var extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : "";
var loader = null;
for (var _i = 0, _a = Engine2._TextureLoaders; _i < _a.length; _i++) {
var availableLoader = _a[_i];
if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
loader = availableLoader;
break;
}
}
if (loader) {
url = loader.transformUrl(url, this._textureFormatInUse);
}
if (scene) {
scene._addPendingData(texture);
}
texture.url = url;
texture.generateMipMaps = !noMipmap;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
if (!this._doNotHandleContextLost) {
texture._buffer = buffer;
}
var onLoadObserver = null;
if (onLoad && !fallback) {
onLoadObserver = texture.onLoadedObservable.add(onLoad);
}
if (!fallback) {
this._internalTexturesCache.push(texture);
}
var onInternalError = function(message, exception) {
if (scene) {
scene._removePendingData(texture);
}
var customFallback = false;
if (loader) {
var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
if (fallbackUrl) {
customFallback = true;
_this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
}
}
if (!customFallback) {
if (onLoadObserver) {
texture.onLoadedObservable.remove(onLoadObserver);
}
if (BABYLON2.Tools.UseFallbackTexture) {
_this.createTexture(BABYLON2.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
}
}
if (onError) {
onError(message || "Unknown error", exception);
}
};
if (loader) {
var callback = function(data2) {
loader.loadData(data2, texture, function(width, height, loadMipmap, isCompressed, done) {
_this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function() {
done();
return false;
}, samplingMode);
});
};
if (!buffer) {
this._loadFile(url, callback, void 0, scene ? scene.database : void 0, true, function(request, exception) {
onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
});
} else {
callback(buffer);
}
} else {
var onload = function(img) {
if (fromBlob && !_this._doNotHandleContextLost) {
texture._buffer = img;
}
_this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function(potWidth, potHeight, continuationCallback) {
var gl = _this._gl;
var isPot = img.width === potWidth && img.height === potHeight;
var internalFormat = format ? _this._getInternalFormat(format) : extension === ".jpg" ? gl.RGB : gl.RGBA;
if (isPot) {
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
return false;
}
var maxTextureSize = _this._caps.maxTextureSize;
if (img.width > maxTextureSize || img.height > maxTextureSize) {
_this._prepareWorkingCanvas();
if (!_this._workingCanvas || !_this._workingContext) {
return false;
}
_this._workingCanvas.width = potWidth;
_this._workingCanvas.height = potHeight;
_this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
texture.width = potWidth;
texture.height = potHeight;
return false;
} else {
var source_1 = new BABYLON2.InternalTexture(_this, BABYLON2.InternalTexture.DATASOURCE_TEMP);
_this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
_this._rescaleTexture(source_1, texture, scene, internalFormat, function() {
_this._releaseTexture(source_1);
_this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
continuationCallback();
});
}
return true;
}, samplingMode);
};
if (!fromData || isBase64) {
if (buffer instanceof HTMLImageElement) {
onload(buffer);
} else {
BABYLON2.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
}
} else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
BABYLON2.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
} else {
onload(buffer);
}
}
return texture;
};
Engine2.prototype._rescaleTexture = function(source, destination, scene, internalFormat, onComplete) {
var _this = this;
var rtt = this.createRenderTargetTexture({
width: destination.width,
height: destination.height
}, {
generateMipMaps: false,
type: Engine2.TEXTURETYPE_UNSIGNED_INT,
samplingMode: Engine2.TEXTURE_BILINEAR_SAMPLINGMODE,
generateDepthBuffer: false,
generateStencilBuffer: false
});
if (!this._rescalePostProcess) {
this._rescalePostProcess = new BABYLON2.PassPostProcess("rescale", 1, null, Engine2.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine2.TEXTURETYPE_UNSIGNED_INT);
}
this._rescalePostProcess.getEffect().executeWhenCompiled(function() {
_this._rescalePostProcess.onApply = function(effect) {
effect._bindTexture("textureSampler", source);
};
var hostingScene = scene;
if (!hostingScene) {
hostingScene = _this.scenes[_this.scenes.length - 1];
}
hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
_this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
_this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
_this.unBindFramebuffer(rtt);
_this._releaseTexture(rtt);
if (onComplete) {
onComplete();
}
});
};
Engine2.prototype.updateRawTexture = function(texture, data2, format, invertY, compression, type) {
if (compression === void 0) {
compression = null;
}
if (type === void 0) {
type = Engine2.TEXTURETYPE_UNSIGNED_INT;
}
if (!texture) {
return;
}
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
var internalFormat = this._getInternalFormat(format);
var textureType = this._getWebGLTextureType(type);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
this._unpackFlipY(invertY === void 0 ? true : invertY ? true : false);
if (!this._doNotHandleContextLost) {
texture._bufferView = data2;
texture.format = format;
texture.type = type;
texture.invertY = invertY;
texture._compression = compression;
}
if (texture.width % 4 !== 0) {
this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
}
if (compression && data2) {
this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data2);
} else {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data2);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
texture.isReady = true;
};
Engine2.prototype.createRawTexture = function(data2, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
if (compression === void 0) {
compression = null;
}
if (type === void 0) {
type = Engine2.TEXTURETYPE_UNSIGNED_INT;
}
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_RAW);
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.format = format;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
texture._compression = compression;
texture.type = type;
if (!this._doNotHandleContextLost) {
texture._bufferView = data2;
}
this.updateRawTexture(texture, data2, format, invertY, compression, type);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._internalTexturesCache.push(texture);
return texture;
};
Engine2.prototype._unpackFlipY = function(value) {
if (this._unpackFlipYCached !== value) {
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
if (this.enableUnpackFlipYCached) {
this._unpackFlipYCached = value;
}
}
};
Engine2.prototype._getUnpackAlignement = function() {
return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
};
Engine2.prototype.createDynamicTexture = function(width, height, generateMipMaps, samplingMode) {
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_DYNAMIC);
texture.baseWidth = width;
texture.baseHeight = height;
if (generateMipMaps) {
width = this.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
height = this.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
}
texture.width = width;
texture.height = height;
texture.isReady = false;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
this.updateTextureSamplingMode(samplingMode, texture);
this._internalTexturesCache.push(texture);
return texture;
};
Engine2.prototype.updateTextureSamplingMode = function(samplingMode, texture) {
var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
if (texture.isCube) {
this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
} else if (texture.is3D) {
this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
} else {
this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
}
texture.samplingMode = samplingMode;
};
Engine2.prototype.updateDynamicTexture = function(texture, canvas2, invertY, premulAlpha, format) {
if (premulAlpha === void 0) {
premulAlpha = false;
}
if (!texture) {
return;
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
this._unpackFlipY(invertY);
if (premulAlpha) {
this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
}
var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas2);
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
if (premulAlpha) {
this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
}
texture.isReady = true;
};
Engine2.prototype.updateVideoTexture = function(texture, video, invertY) {
if (!texture || texture._isDisabled) {
return;
}
var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
this._unpackFlipY(!invertY);
try {
if (this._videoTextureSupported === void 0) {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
if (this._gl.getError() !== 0) {
this._videoTextureSupported = false;
} else {
this._videoTextureSupported = true;
}
}
if (!this._videoTextureSupported) {
if (!texture._workingCanvas) {
texture._workingCanvas = document.createElement("canvas");
var context = texture._workingCanvas.getContext("2d");
if (!context) {
throw new Error("Unable to get 2d context");
}
texture._workingContext = context;
texture._workingCanvas.width = texture.width;
texture._workingCanvas.height = texture.height;
}
texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
} else {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
if (!wasPreviouslyBound) {
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
}
texture.isReady = true;
} catch (ex) {
texture._isDisabled = true;
}
};
Engine2.prototype.updateTextureComparisonFunction = function(texture, comparisonFunction) {
if (this.webGLVersion === 1) {
BABYLON2.Tools.Error("WebGL 1 does not support texture comparison.");
return;
}
var gl = this._gl;
if (texture.isCube) {
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
if (comparisonFunction === 0) {
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine2.LEQUAL);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
} else {
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
} else {
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
if (comparisonFunction === 0) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine2.LEQUAL);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
} else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
}
texture._comparisonFunction = comparisonFunction;
};
Engine2.prototype._setupDepthStencilTexture = function(internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
var width = size.width || size;
var height = size.height || size;
internalTexture.baseWidth = width;
internalTexture.baseHeight = height;
internalTexture.width = width;
internalTexture.height = height;
internalTexture.isReady = true;
internalTexture.samples = 1;
internalTexture.generateMipMaps = false;
internalTexture._generateDepthBuffer = true;
internalTexture._generateStencilBuffer = generateStencil;
internalTexture.samplingMode = bilinearFiltering ? Engine2.TEXTURE_BILINEAR_SAMPLINGMODE : Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
internalTexture.type = Engine2.TEXTURETYPE_UNSIGNED_INT;
internalTexture._comparisonFunction = comparisonFunction;
var gl = this._gl;
var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
if (comparisonFunction === 0) {
gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine2.LEQUAL);
gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
} else {
gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
}
};
Engine2.prototype.createDepthStencilTexture = function(size, options) {
if (options.isCube) {
var width = size.width || size;
return this._createDepthStencilCubeTexture(width, options);
} else {
return this._createDepthStencilTexture(size, options);
}
};
Engine2.prototype._createDepthStencilTexture = function(size, options) {
var internalTexture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_DEPTHTEXTURE);
if (!this._caps.depthTextureExtension) {
BABYLON2.Tools.Error("Depth texture is not supported by your browser or hardware.");
return internalTexture;
}
var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
var gl = this._gl;
this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
if (this.webGLVersion > 1) {
if (internalOptions.generateStencil) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
}
} else {
if (internalOptions.generateStencil) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
}
}
this._bindTextureDirectly(gl.TEXTURE_2D, null);
return internalTexture;
};
Engine2.prototype._createDepthStencilCubeTexture = function(size, options) {
var internalTexture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_UNKNOWN);
internalTexture.isCube = true;
if (this.webGLVersion === 1) {
BABYLON2.Tools.Error("Depth cube texture is not supported by WebGL 1.");
return internalTexture;
}
var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
var gl = this._gl;
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
for (var face = 0; face < 6; face++) {
if (internalOptions.generateStencil) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
} else {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
}
}
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
return internalTexture;
};
Engine2.prototype.setFrameBufferDepthStencilTexture = function(renderTarget) {
var internalTexture = renderTarget.getInternalTexture();
if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
return;
}
var gl = this._gl;
var depthStencilTexture = renderTarget.depthStencilTexture;
this.bindUnboundFramebuffer(internalTexture._framebuffer);
if (depthStencilTexture.isCube) {
if (depthStencilTexture._generateStencilBuffer) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
} else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
}
} else {
if (depthStencilTexture._generateStencilBuffer) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
} else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
}
}
this.bindUnboundFramebuffer(null);
};
Engine2.prototype.createRenderTargetTexture = function(size, options) {
var fullOptions = new RenderTargetCreationOptions();
if (options !== void 0 && typeof options === "object") {
fullOptions.generateMipMaps = options.generateMipMaps;
fullOptions.generateDepthBuffer = options.generateDepthBuffer === void 0 ? true : options.generateDepthBuffer;
fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
fullOptions.type = options.type === void 0 ? Engine2.TEXTURETYPE_UNSIGNED_INT : options.type;
fullOptions.samplingMode = options.samplingMode === void 0 ? Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
fullOptions.format = options.format === void 0 ? Engine2.TEXTUREFORMAT_RGBA : options.format;
} else {
fullOptions.generateMipMaps = options;
fullOptions.generateDepthBuffer = true;
fullOptions.generateStencilBuffer = false;
fullOptions.type = Engine2.TEXTURETYPE_UNSIGNED_INT;
fullOptions.samplingMode = Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE;
fullOptions.format = Engine2.TEXTUREFORMAT_RGBA;
}
if (fullOptions.type === Engine2.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
fullOptions.samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
} else if (fullOptions.type === Engine2.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
fullOptions.samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
}
var gl = this._gl;
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_RENDERTARGET);
this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
var width = size.width || size;
var height = size.height || size;
var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
if (fullOptions.type === Engine2.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
fullOptions.type = Engine2.TEXTURETYPE_UNSIGNED_INT;
BABYLON2.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
}
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
var currentFrameBuffer = this._currentFramebuffer;
var framebuffer = gl.createFramebuffer();
this.bindUnboundFramebuffer(framebuffer);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
if (fullOptions.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(gl.TEXTURE_2D, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(currentFrameBuffer);
texture._framebuffer = framebuffer;
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture.format = fullOptions.format;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
this._internalTexturesCache.push(texture);
return texture;
};
Engine2.prototype.createMultipleRenderTarget = function(size, options) {
var generateMipMaps = false;
var generateDepthBuffer = true;
var generateStencilBuffer = false;
var generateDepthTexture = false;
var textureCount = 1;
var defaultType = Engine2.TEXTURETYPE_UNSIGNED_INT;
var defaultSamplingMode = Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE;
var types = new Array();
var samplingModes = new Array();
if (options !== void 0) {
generateMipMaps = options.generateMipMaps === void 0 ? false : options.generateMipMaps;
generateDepthBuffer = options.generateDepthBuffer === void 0 ? true : options.generateDepthBuffer;
generateStencilBuffer = options.generateStencilBuffer === void 0 ? false : options.generateStencilBuffer;
generateDepthTexture = options.generateDepthTexture === void 0 ? false : options.generateDepthTexture;
textureCount = options.textureCount || 1;
if (options.types) {
types = options.types;
}
if (options.samplingModes) {
samplingModes = options.samplingModes;
}
}
var gl = this._gl;
var framebuffer = gl.createFramebuffer();
this.bindUnboundFramebuffer(framebuffer);
var width = size.width || size;
var height = size.height || size;
var textures = [];
var attachments = [];
var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
for (var i2 = 0; i2 < textureCount; i2++) {
var samplingMode = samplingModes[i2] || defaultSamplingMode;
var type = types[i2] || defaultType;
if (type === Engine2.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
} else if (type === Engine2.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
}
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
if (type === Engine2.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
type = Engine2.TEXTURETYPE_UNSIGNED_INT;
BABYLON2.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
}
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i2 : "COLOR_ATTACHMENT" + i2 + "_WEBGL"];
textures.push(texture);
attachments.push(attachment);
gl.activeTexture(gl["TEXTURE" + i2]);
gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(gl.TEXTURE_2D, null);
texture._framebuffer = framebuffer;
texture._depthStencilBuffer = depthStencilBuffer;
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.type = type;
texture._generateDepthBuffer = generateDepthBuffer;
texture._generateStencilBuffer = generateStencilBuffer;
texture._attachments = attachments;
this._internalTexturesCache.push(texture);
}
if (generateDepthTexture && this._caps.depthTextureExtension) {
var depthTexture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
depthTexture._framebuffer = framebuffer;
depthTexture.baseWidth = width;
depthTexture.baseHeight = height;
depthTexture.width = width;
depthTexture.height = height;
depthTexture.isReady = true;
depthTexture.samples = 1;
depthTexture.generateMipMaps = generateMipMaps;
depthTexture.samplingMode = gl.NEAREST;
depthTexture._generateDepthBuffer = generateDepthBuffer;
depthTexture._generateStencilBuffer = generateStencilBuffer;
textures.push(depthTexture);
this._internalTexturesCache.push(depthTexture);
}
gl.drawBuffers(attachments);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(null);
this.resetTextureCache();
return textures;
};
Engine2.prototype._setupFramebufferDepthAttachments = function(generateStencilBuffer, generateDepthBuffer, width, height, samples) {
if (samples === void 0) {
samples = 1;
}
var depthStencilBuffer = null;
var gl = this._gl;
if (generateStencilBuffer) {
depthStencilBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
if (samples > 1) {
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
} else {
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
}
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
} else if (generateDepthBuffer) {
depthStencilBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
if (samples > 1) {
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
} else {
gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
}
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
}
return depthStencilBuffer;
};
Engine2.prototype.updateRenderTargetTextureSampleCount = function(texture, samples) {
if (this.webGLVersion < 2 || !texture) {
return 1;
}
if (texture.samples === samples) {
return samples;
}
var gl = this._gl;
samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
if (texture._depthStencilBuffer) {
gl.deleteRenderbuffer(texture._depthStencilBuffer);
texture._depthStencilBuffer = null;
}
if (texture._MSAAFramebuffer) {
gl.deleteFramebuffer(texture._MSAAFramebuffer);
texture._MSAAFramebuffer = null;
}
if (texture._MSAARenderBuffer) {
gl.deleteRenderbuffer(texture._MSAARenderBuffer);
texture._MSAARenderBuffer = null;
}
if (samples > 1) {
var framebuffer = gl.createFramebuffer();
if (!framebuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
texture._MSAAFramebuffer = framebuffer;
this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
var colorRenderbuffer = gl.createRenderbuffer();
if (!colorRenderbuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
texture._MSAARenderBuffer = colorRenderbuffer;
} else {
this.bindUnboundFramebuffer(texture._framebuffer);
}
texture.samples = samples;
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(null);
return samples;
};
Engine2.prototype.updateMultipleRenderTargetTextureSampleCount = function(textures, samples) {
if (this.webGLVersion < 2 || !textures || textures.length == 0) {
return 1;
}
if (textures[0].samples === samples) {
return samples;
}
var gl = this._gl;
samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
if (textures[0]._depthStencilBuffer) {
gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
textures[0]._depthStencilBuffer = null;
}
if (textures[0]._MSAAFramebuffer) {
gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
textures[0]._MSAAFramebuffer = null;
}
for (var i2 = 0; i2 < textures.length; i2++) {
if (textures[i2]._MSAARenderBuffer) {
gl.deleteRenderbuffer(textures[i2]._MSAARenderBuffer);
textures[i2]._MSAARenderBuffer = null;
}
}
if (samples > 1) {
var framebuffer = gl.createFramebuffer();
if (!framebuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
this.bindUnboundFramebuffer(framebuffer);
var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
var attachments = [];
for (var i2 = 0; i2 < textures.length; i2++) {
var texture = textures[i2];
var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i2 : "COLOR_ATTACHMENT" + i2 + "_WEBGL"];
var colorRenderbuffer = gl.createRenderbuffer();
if (!colorRenderbuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
texture._MSAAFramebuffer = framebuffer;
texture._MSAARenderBuffer = colorRenderbuffer;
texture.samples = samples;
texture._depthStencilBuffer = depthStencilBuffer;
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
attachments.push(attachment);
}
gl.drawBuffers(attachments);
} else {
this.bindUnboundFramebuffer(textures[0]._framebuffer);
}
this.bindUnboundFramebuffer(null);
return samples;
};
Engine2.prototype._uploadCompressedDataToTextureDirectly = function(texture, internalFormat, width, height, data2, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
var gl = this._gl;
var target = gl.TEXTURE_2D;
if (texture.isCube) {
target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
}
this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data2);
};
Engine2.prototype._uploadDataToTextureDirectly = function(texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
var gl = this._gl;
var textureType = this._getWebGLTextureType(texture.type);
var format = this._getInternalFormat(texture.format);
var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
this._unpackFlipY(texture.invertY);
var target = gl.TEXTURE_2D;
if (texture.isCube) {
target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
}
var lodMaxWidth = Math.round(BABYLON2.Scalar.Log2(texture.width));
var lodMaxHeight = Math.round(BABYLON2.Scalar.Log2(texture.height));
var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
};
Engine2.prototype._uploadArrayBufferViewToTexture = function(texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
var gl = this._gl;
var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
this._bindTextureDirectly(bindTarget, texture, true);
this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
this._bindTextureDirectly(bindTarget, null, true);
};
Engine2.prototype._uploadImageToTexture = function(texture, image, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
var gl = this._gl;
var textureType = this._getWebGLTextureType(texture.type);
var format = this._getInternalFormat(texture.format);
var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
this._bindTextureDirectly(bindTarget, texture, true);
this._unpackFlipY(texture.invertY);
var target = gl.TEXTURE_2D;
if (texture.isCube) {
target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
}
gl.texImage2D(target, lod, internalFormat, format, textureType, image);
this._bindTextureDirectly(bindTarget, null, true);
};
Engine2.prototype.createRenderTargetCubeTexture = function(size, options) {
var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine2.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine2.TEXTUREFORMAT_RGBA }, options);
fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
if (fullOptions.type === Engine2.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
fullOptions.samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
} else if (fullOptions.type === Engine2.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
fullOptions.samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
}
var gl = this._gl;
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_RENDERTARGET);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
if (fullOptions.type === Engine2.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
fullOptions.type = Engine2.TEXTURETYPE_UNSIGNED_INT;
BABYLON2.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
}
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
for (var face = 0; face < 6; face++) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
}
var framebuffer = gl.createFramebuffer();
this.bindUnboundFramebuffer(framebuffer);
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
if (fullOptions.generateMipMaps) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
this.bindUnboundFramebuffer(null);
texture._framebuffer = framebuffer;
texture.width = size;
texture.height = size;
texture.isReady = true;
texture.isCube = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture.format = fullOptions.format;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
this._internalTexturesCache.push(texture);
return texture;
};
Engine2.prototype.createPrefilteredCubeTexture = function(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
var _this = this;
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (forcedExtension === void 0) {
forcedExtension = null;
}
if (createPolynomials === void 0) {
createPolynomials = true;
}
var callback = function(loadData) {
if (!loadData) {
if (onLoad) {
onLoad(null);
}
return;
}
var texture = loadData.texture;
if (!createPolynomials) {
texture._sphericalPolynomial = new BABYLON2.SphericalPolynomial();
} else if (loadData.info.sphericalPolynomial) {
texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
}
texture._dataSource = BABYLON2.InternalTexture.DATASOURCE_CUBEPREFILTERED;
if (_this._caps.textureLOD) {
if (onLoad) {
onLoad(texture);
}
return;
}
var mipSlices = 3;
var gl = _this._gl;
var width = loadData.width;
if (!width) {
return;
}
var textures = [];
for (var i2 = 0; i2 < mipSlices; i2++) {
var smoothness = i2 / (mipSlices - 1);
var roughness = 1 - smoothness;
var minLODIndex = lodOffset;
var maxLODIndex = BABYLON2.Scalar.Log2(width) * lodScale + lodOffset;
var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
var glTextureFromLod = new BABYLON2.InternalTexture(_this, BABYLON2.InternalTexture.DATASOURCE_TEMP);
glTextureFromLod.type = texture.type;
glTextureFromLod.format = texture.format;
glTextureFromLod.width = Math.pow(2, Math.max(BABYLON2.Scalar.Log2(width) - mipmapIndex, 0));
glTextureFromLod.height = glTextureFromLod.width;
glTextureFromLod.isCube = true;
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
if (loadData.isDDS) {
var info = loadData.info;
var data2 = loadData.data;
_this._unpackFlipY(info.isCompressed);
BABYLON2.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data2, info, true, 6, mipmapIndex);
} else {
BABYLON2.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
var lodTexture = new BABYLON2.BaseTexture(scene);
lodTexture.isCube = true;
lodTexture._texture = glTextureFromLod;
glTextureFromLod.isReady = true;
textures.push(lodTexture);
}
texture._lodTextureHigh = textures[2];
texture._lodTextureMid = textures[1];
texture._lodTextureLow = textures[0];
if (onLoad) {
onLoad(texture);
}
};
return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
};
Engine2.prototype.createCubeTexture = function(rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
var _this = this;
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (forcedExtension === void 0) {
forcedExtension = null;
}
if (createPolynomials === void 0) {
createPolynomials = false;
}
if (lodScale === void 0) {
lodScale = 0;
}
if (lodOffset === void 0) {
lodOffset = 0;
}
if (fallback === void 0) {
fallback = null;
}
var gl = this._gl;
var texture = fallback ? fallback : new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_CUBE);
texture.isCube = true;
texture.url = rootUrl;
texture.generateMipMaps = !noMipmap;
texture._lodGenerationScale = lodScale;
texture._lodGenerationOffset = lodOffset;
if (!this._doNotHandleContextLost) {
texture._extension = forcedExtension;
texture._files = files;
}
var lastDot = rootUrl.lastIndexOf(".");
var extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "";
var loader = null;
for (var _i = 0, _a = Engine2._TextureLoaders; _i < _a.length; _i++) {
var availableLoader = _a[_i];
if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
loader = availableLoader;
break;
}
}
var onInternalError = function(request, exception) {
if (loader) {
var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
if (fallbackUrl) {
_this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
}
}
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
};
if (loader) {
rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
var onloaddata = function(data2) {
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
loader.loadCubeData(data2, texture, createPolynomials, onLoad, onError);
};
if (files && files.length === 6) {
if (loader.supportCascades) {
this._cascadeLoadFiles(scene, onloaddata, files, onError);
} else if (onError) {
onError("Textures type does not support cascades.");
}
} else {
this._loadFile(rootUrl, onloaddata, void 0, void 0, true, onInternalError);
}
} else {
if (!files) {
throw new Error("Cannot load cubemap because files were not defined");
}
this._cascadeLoadImgs(rootUrl, scene, function(imgs) {
var width = _this.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
var height = width;
_this._prepareWorkingCanvas();
if (!_this._workingCanvas || !_this._workingContext) {
return;
}
_this._workingCanvas.width = width;
_this._workingCanvas.height = height;
var faces = [
gl.TEXTURE_CUBE_MAP_POSITIVE_X,
gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
];
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
_this._unpackFlipY(false);
var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
for (var index = 0; index < faces.length; index++) {
_this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
}
if (!noMipmap) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
_this._setCubeMapTextureParams(!noMipmap);
texture.width = width;
texture.height = height;
texture.isReady = true;
if (format) {
texture.format = format;
}
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}, files, onError);
}
this._internalTexturesCache.push(texture);
return texture;
};
Engine2.prototype._setCubeMapTextureParams = function(loadMipmap) {
var gl = this._gl;
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
};
Engine2.prototype.updateRawCubeTexture = function(texture, data2, format, type, invertY, compression, level) {
if (compression === void 0) {
compression = null;
}
if (level === void 0) {
level = 0;
}
texture._bufferViewArray = data2;
texture.format = format;
texture.type = type;
texture.invertY = invertY;
texture._compression = compression;
var gl = this._gl;
var textureType = this._getWebGLTextureType(type);
var internalFormat = this._getInternalFormat(format);
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
var needConversion = false;
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
needConversion = true;
}
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
this._unpackFlipY(invertY === void 0 ? true : invertY ? true : false);
if (texture.width % 4 !== 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
}
for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
var faceData = data2[faceIndex];
if (compression) {
gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
} else {
if (needConversion) {
faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
}
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
}
}
var isPot = !this.needPOTTextures || BABYLON2.Tools.IsExponentOfTwo(texture.width) && BABYLON2.Tools.IsExponentOfTwo(texture.height);
if (isPot && texture.generateMipMaps && level === 0) {
this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
texture.isReady = true;
};
Engine2.prototype.createRawCubeTexture = function(data2, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
if (compression === void 0) {
compression = null;
}
var gl = this._gl;
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_CUBERAW);
texture.isCube = true;
texture.format = format;
texture.type = type;
if (!this._doNotHandleContextLost) {
texture._bufferViewArray = data2;
}
var textureType = this._getWebGLTextureType(type);
var internalFormat = this._getInternalFormat(format);
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
}
if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
generateMipMaps = false;
samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
BABYLON2.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
} else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
generateMipMaps = false;
samplingMode = Engine2.TEXTURE_NEAREST_SAMPLINGMODE;
BABYLON2.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
} else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
generateMipMaps = false;
BABYLON2.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
} else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
generateMipMaps = false;
BABYLON2.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
}
var width = size;
var height = width;
texture.width = width;
texture.height = height;
var isPot = !this.needPOTTextures || BABYLON2.Tools.IsExponentOfTwo(texture.width) && BABYLON2.Tools.IsExponentOfTwo(texture.height);
if (!isPot) {
generateMipMaps = false;
}
if (data2) {
this.updateRawCubeTexture(texture, data2, format, type, invertY, compression);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
if (data2 && generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
}
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
texture.generateMipMaps = generateMipMaps;
return texture;
};
Engine2.prototype.createRawCubeTextureFromUrl = function(url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
var _this = this;
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (samplingMode === void 0) {
samplingMode = Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE;
}
if (invertY === void 0) {
invertY = false;
}
var gl = this._gl;
var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
scene._addPendingData(texture);
texture.url = url;
this._internalTexturesCache.push(texture);
var onerror = function(request, exception) {
scene._removePendingData(texture);
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
};
var internalCallback = function(data2) {
var width = texture.width;
var faceDataArrays = callback(data2);
if (!faceDataArrays) {
return;
}
if (mipmapGenerator) {
var textureType = _this._getWebGLTextureType(type);
var internalFormat = _this._getInternalFormat(format);
var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
var needConversion = false;
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
needConversion = true;
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
_this._unpackFlipY(false);
var mipData = mipmapGenerator(faceDataArrays);
for (var level = 0; level < mipData.length; level++) {
var mipSize = width >> level;
for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
var mipFaceData = mipData[level][faceIndex];
if (needConversion) {
mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
}
gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
}
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
} else {
_this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
}
texture.isReady = true;
scene._removePendingData(texture);
if (onLoad) {
onLoad();
}
};
this._loadFile(url, function(data2) {
internalCallback(data2);
}, void 0, scene.database, true, onerror);
return texture;
};
Engine2.prototype.updateRawTexture3D = function(texture, data2, format, invertY, compression, textureType) {
if (compression === void 0) {
compression = null;
}
if (textureType === void 0) {
textureType = Engine2.TEXTURETYPE_UNSIGNED_INT;
}
var internalType = this._getWebGLTextureType(textureType);
var internalFormat = this._getInternalFormat(format);
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
this._unpackFlipY(invertY === void 0 ? true : invertY ? true : false);
if (!this._doNotHandleContextLost) {
texture._bufferView = data2;
texture.format = format;
texture.invertY = invertY;
texture._compression = compression;
}
if (texture.width % 4 !== 0) {
this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
}
if (compression && data2) {
this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data2);
} else {
this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data2);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_3D);
}
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
texture.isReady = true;
};
Engine2.prototype.createRawTexture3D = function(data2, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
if (compression === void 0) {
compression = null;
}
if (textureType === void 0) {
textureType = Engine2.TEXTURETYPE_UNSIGNED_INT;
}
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_RAW3D);
texture.baseWidth = width;
texture.baseHeight = height;
texture.baseDepth = depth;
texture.width = width;
texture.height = height;
texture.depth = depth;
texture.format = format;
texture.type = textureType;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.is3D = true;
if (!this._doNotHandleContextLost) {
texture._bufferView = data2;
}
this.updateRawTexture3D(texture, data2, format, invertY, compression, textureType);
this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_3D);
}
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
this._internalTexturesCache.push(texture);
return texture;
};
Engine2.prototype._prepareWebGLTextureContinuation = function(texture, scene, noMipmap, isCompressed, samplingMode) {
var gl = this._gl;
if (!gl) {
return;
}
var filters = this._getSamplingParameters(samplingMode, !noMipmap);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
if (!noMipmap && !isCompressed) {
gl.generateMipmap(gl.TEXTURE_2D);
}
this._bindTextureDirectly(gl.TEXTURE_2D, null);
if (scene) {
scene._removePendingData(texture);
}
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
};
Engine2.prototype._prepareWebGLTexture = function(texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
var _this = this;
if (samplingMode === void 0) {
samplingMode = Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE;
}
var maxTextureSize = this.getCaps().maxTextureSize;
var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
var gl = this._gl;
if (!gl) {
return;
}
if (!texture._webGLTexture) {
if (scene) {
scene._removePendingData(texture);
}
return;
}
this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
this._unpackFlipY(invertY === void 0 ? true : invertY ? true : false);
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = potWidth;
texture.height = potHeight;
texture.isReady = true;
if (processFunction(potWidth, potHeight, function() {
_this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
})) {
return;
}
this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
};
Engine2.prototype._convertRGBtoRGBATextureData = function(rgbData, width, height, textureType) {
var rgbaData;
if (textureType === Engine2.TEXTURETYPE_FLOAT) {
rgbaData = new Float32Array(width * height * 4);
} else {
rgbaData = new Uint32Array(width * height * 4);
}
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
var index = (y * width + x) * 3;
var newIndex = (y * width + x) * 4;
rgbaData[newIndex + 0] = rgbData[index + 0];
rgbaData[newIndex + 1] = rgbData[index + 1];
rgbaData[newIndex + 2] = rgbData[index + 2];
rgbaData[newIndex + 3] = 1;
}
}
return rgbaData;
};
Engine2.prototype._releaseFramebufferObjects = function(texture) {
var gl = this._gl;
if (texture._framebuffer) {
gl.deleteFramebuffer(texture._framebuffer);
texture._framebuffer = null;
}
if (texture._depthStencilBuffer) {
gl.deleteRenderbuffer(texture._depthStencilBuffer);
texture._depthStencilBuffer = null;
}
if (texture._MSAAFramebuffer) {
gl.deleteFramebuffer(texture._MSAAFramebuffer);
texture._MSAAFramebuffer = null;
}
if (texture._MSAARenderBuffer) {
gl.deleteRenderbuffer(texture._MSAARenderBuffer);
texture._MSAARenderBuffer = null;
}
};
Engine2.prototype._releaseTexture = function(texture) {
var gl = this._gl;
this._releaseFramebufferObjects(texture);
gl.deleteTexture(texture._webGLTexture);
this.unbindAllTextures();
var index = this._internalTexturesCache.indexOf(texture);
if (index !== -1) {
this._internalTexturesCache.splice(index, 1);
}
if (texture._lodTextureHigh) {
texture._lodTextureHigh.dispose();
}
if (texture._lodTextureMid) {
texture._lodTextureMid.dispose();
}
if (texture._lodTextureLow) {
texture._lodTextureLow.dispose();
}
this.scenes.forEach(function(scene) {
scene.postProcesses.forEach(function(postProcess) {
if (postProcess._outputTexture == texture) {
postProcess._outputTexture = null;
}
});
scene.cameras.forEach(function(camera2) {
camera2._postProcesses.forEach(function(postProcess) {
if (postProcess) {
if (postProcess._outputTexture == texture) {
postProcess._outputTexture = null;
}
}
});
});
});
};
Engine2.prototype.setProgram = function(program) {
if (this._currentProgram !== program) {
this._gl.useProgram(program);
this._currentProgram = program;
}
};
Engine2.prototype.bindSamplers = function(effect) {
this.setProgram(effect.getProgram());
var samplers = effect.getSamplers();
for (var index = 0; index < samplers.length; index++) {
var uniform = effect.getUniform(samplers[index]);
if (uniform) {
this._boundUniforms[index] = uniform;
}
}
this._currentEffect = null;
};
Engine2.prototype._moveBoundTextureOnTop = function(internalTexture) {
if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
return;
}
this._linkTrackers(internalTexture.previous, internalTexture.next);
this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
};
Engine2.prototype._getCorrectTextureChannel = function(channel, internalTexture) {
if (!internalTexture) {
return -1;
}
internalTexture._initialSlot = channel;
if (this.disableTextureBindingOptimization) {
if (channel !== internalTexture._designatedSlot) {
this._textureCollisions.addCount(1, false);
}
} else {
if (channel !== internalTexture._designatedSlot) {
if (internalTexture._designatedSlot > -1) {
return internalTexture._designatedSlot;
} else {
if (this._nextFreeTextureSlots.length) {
return this._nextFreeTextureSlots[0];
}
this._textureCollisions.addCount(1, false);
return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
}
}
}
return channel;
};
Engine2.prototype._linkTrackers = function(previous, next) {
previous.next = next;
next.previous = previous;
};
Engine2.prototype._removeDesignatedSlot = function(internalTexture) {
var currentSlot = internalTexture._designatedSlot;
if (currentSlot === -1) {
return -1;
}
internalTexture._designatedSlot = -1;
if (this.disableTextureBindingOptimization) {
return -1;
}
this._linkTrackers(internalTexture.previous, internalTexture.next);
this._boundTexturesCache[currentSlot] = null;
this._nextFreeTextureSlots.push(currentSlot);
return currentSlot;
};
Engine2.prototype._activateCurrentTexture = function() {
if (this._currentTextureChannel !== this._activeChannel) {
this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
this._currentTextureChannel = this._activeChannel;
}
};
Engine2.prototype._bindTextureDirectly = function(target, texture, forTextureDataUpdate, force) {
if (forTextureDataUpdate === void 0) {
forTextureDataUpdate = false;
}
if (force === void 0) {
force = false;
}
var wasPreviouslyBound = false;
if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
this._activeChannel = texture._designatedSlot;
}
var currentTextureBound = this._boundTexturesCache[this._activeChannel];
var isTextureForRendering = texture && texture._initialSlot > -1;
if (currentTextureBound !== texture || force) {
if (currentTextureBound) {
this._removeDesignatedSlot(currentTextureBound);
}
this._activateCurrentTexture();
this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
this._boundTexturesCache[this._activeChannel] = texture;
if (texture) {
if (!this.disableTextureBindingOptimization) {
var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
if (slotIndex > -1) {
this._nextFreeTextureSlots.splice(slotIndex, 1);
}
this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
}
texture._designatedSlot = this._activeChannel;
}
} else if (forTextureDataUpdate) {
wasPreviouslyBound = true;
this._activateCurrentTexture();
}
if (isTextureForRendering && !forTextureDataUpdate) {
this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
}
return wasPreviouslyBound;
};
Engine2.prototype._bindTexture = function(channel, texture) {
if (channel < 0) {
return;
}
if (texture) {
channel = this._getCorrectTextureChannel(channel, texture);
}
this._activeChannel = channel;
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
};
Engine2.prototype.setTextureFromPostProcess = function(channel, postProcess) {
this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
};
Engine2.prototype.setTextureFromPostProcessOutput = function(channel, postProcess) {
this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
};
Engine2.prototype.unbindAllTextures = function() {
for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
this._activeChannel = channel;
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
if (this.webGLVersion > 1) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
}
}
};
Engine2.prototype.setTexture = function(channel, uniform, texture) {
if (channel < 0) {
return;
}
if (uniform) {
this._boundUniforms[channel] = uniform;
}
this._setTexture(channel, texture);
};
Engine2.prototype.setDepthStencilTexture = function(channel, uniform, texture) {
if (channel < 0) {
return;
}
if (uniform) {
this._boundUniforms[channel] = uniform;
}
if (!texture || !texture.depthStencilTexture) {
this._setTexture(channel, null);
} else {
this._setTexture(channel, texture, false, true);
}
};
Engine2.prototype._bindSamplerUniformToChannel = function(sourceSlot, destination) {
var uniform = this._boundUniforms[sourceSlot];
if (uniform._currentState === destination) {
return;
}
this._gl.uniform1i(uniform, destination);
uniform._currentState = destination;
};
Engine2.prototype._getTextureWrapMode = function(mode) {
switch (mode) {
case Engine2.TEXTURE_WRAP_ADDRESSMODE:
return this._gl.REPEAT;
case Engine2.TEXTURE_CLAMP_ADDRESSMODE:
return this._gl.CLAMP_TO_EDGE;
case Engine2.TEXTURE_MIRROR_ADDRESSMODE:
return this._gl.MIRRORED_REPEAT;
}
return this._gl.REPEAT;
};
Engine2.prototype._setTexture = function(channel, texture, isPartOfTextureArray, depthStencilTexture) {
if (isPartOfTextureArray === void 0) {
isPartOfTextureArray = false;
}
if (depthStencilTexture === void 0) {
depthStencilTexture = false;
}
if (!texture) {
if (this._boundTexturesCache[channel] != null) {
this._activeChannel = channel;
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
if (this.webGLVersion > 1) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
}
}
return false;
}
if (texture.video) {
this._activeChannel = channel;
texture.update();
} else if (texture.delayLoadState === Engine2.DELAYLOADSTATE_NOTLOADED) {
texture.delayLoad();
return false;
}
var internalTexture;
if (depthStencilTexture) {
internalTexture = texture.depthStencilTexture;
} else if (texture.isReady()) {
internalTexture = texture.getInternalTexture();
} else if (texture.isCube) {
internalTexture = this.emptyCubeTexture;
} else if (texture.is3D) {
internalTexture = this.emptyTexture3D;
} else {
internalTexture = this.emptyTexture;
}
if (!isPartOfTextureArray) {
channel = this._getCorrectTextureChannel(channel, internalTexture);
}
var needToBind = true;
if (this._boundTexturesCache[channel] === internalTexture) {
this._moveBoundTextureOnTop(internalTexture);
if (!isPartOfTextureArray) {
this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
}
needToBind = false;
}
this._activeChannel = channel;
if (internalTexture && internalTexture.is3D) {
if (needToBind) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
}
if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
internalTexture._cachedWrapU = texture.wrapU;
this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
}
if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
internalTexture._cachedWrapV = texture.wrapV;
this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
}
if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
internalTexture._cachedWrapR = texture.wrapR;
this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
}
this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
} else if (internalTexture && internalTexture.isCube) {
if (needToBind) {
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
}
if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
var textureWrapMode = texture.coordinatesMode !== Engine2.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine2.TEXTURE_SKYBOX_MODE ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
}
this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
} else {
if (needToBind) {
this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
}
if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
internalTexture._cachedWrapU = texture.wrapU;
this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
}
if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
internalTexture._cachedWrapV = texture.wrapV;
this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
}
this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
}
return true;
};
Engine2.prototype.setTextureArray = function(channel, uniform, textures) {
if (channel < 0 || !uniform) {
return;
}
if (!this._textureUnits || this._textureUnits.length !== textures.length) {
this._textureUnits = new Int32Array(textures.length);
}
for (var i2 = 0; i2 < textures.length; i2++) {
this._textureUnits[i2] = this._getCorrectTextureChannel(channel + i2, textures[i2].getInternalTexture());
}
this._gl.uniform1iv(uniform, this._textureUnits);
for (var index = 0; index < textures.length; index++) {
this._setTexture(this._textureUnits[index], textures[index], true);
}
};
Engine2.prototype._setAnisotropicLevel = function(target, texture) {
var internalTexture = texture.getInternalTexture();
if (!internalTexture) {
return;
}
var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
var value = texture.anisotropicFilteringLevel;
if (internalTexture.samplingMode !== Engine2.TEXTURE_LINEAR_LINEAR_MIPNEAREST && internalTexture.samplingMode !== Engine2.TEXTURE_LINEAR_LINEAR_MIPLINEAR && internalTexture.samplingMode !== Engine2.TEXTURE_LINEAR_LINEAR) {
value = 1;
}
if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
internalTexture._cachedAnisotropicFilteringLevel = value;
}
};
Engine2.prototype._setTextureParameterFloat = function(target, parameter, value, texture) {
this._bindTextureDirectly(target, texture, true, true);
this._gl.texParameterf(target, parameter, value);
};
Engine2.prototype._setTextureParameterInteger = function(target, parameter, value, texture) {
if (texture) {
this._bindTextureDirectly(target, texture, true, true);
}
this._gl.texParameteri(target, parameter, value);
};
Engine2.prototype.readPixels = function(x, y, width, height) {
var data2 = new Uint8Array(height * width * 4);
this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data2);
return data2;
};
Engine2.prototype.addExternalData = function(key, data2) {
if (!this._externalData) {
this._externalData = new BABYLON2.StringDictionary();
}
return this._externalData.add(key, data2);
};
Engine2.prototype.getExternalData = function(key) {
if (!this._externalData) {
this._externalData = new BABYLON2.StringDictionary();
}
return this._externalData.get(key);
};
Engine2.prototype.getOrAddExternalDataWithFactory = function(key, factory) {
if (!this._externalData) {
this._externalData = new BABYLON2.StringDictionary();
}
return this._externalData.getOrAddWithFactory(key, factory);
};
Engine2.prototype.removeExternalData = function(key) {
if (!this._externalData) {
this._externalData = new BABYLON2.StringDictionary();
}
return this._externalData.remove(key);
};
Engine2.prototype.unbindAllAttributes = function() {
if (this._mustWipeVertexAttributes) {
this._mustWipeVertexAttributes = false;
for (var i2 = 0; i2 < this._caps.maxVertexAttribs; i2++) {
this._gl.disableVertexAttribArray(i2);
this._vertexAttribArraysEnabled[i2] = false;
this._currentBufferPointers[i2].active = false;
}
return;
}
for (var i2 = 0, ul = this._vertexAttribArraysEnabled.length; i2 < ul; i2++) {
if (i2 >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i2]) {
continue;
}
this._gl.disableVertexAttribArray(i2);
this._vertexAttribArraysEnabled[i2] = false;
this._currentBufferPointers[i2].active = false;
}
};
Engine2.prototype.releaseEffects = function() {
for (var name in this._compiledEffects) {
this._deleteProgram(this._compiledEffects[name]._program);
}
this._compiledEffects = {};
};
Engine2.prototype.dispose = function() {
this.hideLoadingUI();
this.stopRenderLoop();
while (this.postProcesses.length) {
this.postProcesses[0].dispose();
}
if (this._emptyTexture) {
this._releaseTexture(this._emptyTexture);
this._emptyTexture = null;
}
if (this._emptyCubeTexture) {
this._releaseTexture(this._emptyCubeTexture);
this._emptyCubeTexture = null;
}
if (this._rescalePostProcess) {
this._rescalePostProcess.dispose();
}
while (this.scenes.length) {
this.scenes[0].dispose();
}
if (Engine2.Instances.length === 1 && Engine2.audioEngine) {
Engine2.audioEngine.dispose();
}
this.releaseEffects();
this.unbindAllAttributes();
this._boundUniforms = [];
if (this._dummyFramebuffer) {
this._gl.deleteFramebuffer(this._dummyFramebuffer);
}
this.disableVR();
if (BABYLON2.Tools.IsWindowObjectExist()) {
window.removeEventListener("blur", this._onBlur);
window.removeEventListener("focus", this._onFocus);
window.removeEventListener("vrdisplaypointerrestricted", this._onVRDisplayPointerRestricted);
window.removeEventListener("vrdisplaypointerunrestricted", this._onVRDisplayPointerUnrestricted);
if (this._renderingCanvas) {
this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
if (!this._doNotHandleContextLost) {
this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
}
}
document.removeEventListener("fullscreenchange", this._onFullscreenChange);
document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
document.removeEventListener("pointerlockchange", this._onPointerLockChange);
document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
if (this._onVrDisplayConnect) {
window.removeEventListener("vrdisplayconnect", this._onVrDisplayConnect);
if (this._onVrDisplayDisconnect) {
window.removeEventListener("vrdisplaydisconnect", this._onVrDisplayDisconnect);
}
if (this._onVrDisplayPresentChange) {
window.removeEventListener("vrdisplaypresentchange", this._onVrDisplayPresentChange);
}
this._onVrDisplayConnect = null;
this._onVrDisplayDisconnect = null;
}
}
var index = Engine2.Instances.indexOf(this);
if (index >= 0) {
Engine2.Instances.splice(index, 1);
}
this._workingCanvas = null;
this._workingContext = null;
this._currentBufferPointers = [];
this._renderingCanvas = null;
this._currentProgram = null;
this._bindedRenderFunction = null;
this.onResizeObservable.clear();
this.onCanvasBlurObservable.clear();
this.onCanvasFocusObservable.clear();
this.onCanvasPointerOutObservable.clear();
this.onBeginFrameObservable.clear();
this.onEndFrameObservable.clear();
BABYLON2.Effect.ResetCache();
for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
var request = _a[_i];
request.abort();
}
};
Engine2.prototype.displayLoadingUI = function() {
if (!BABYLON2.Tools.IsWindowObjectExist()) {
return;
}
var loadingScreen = this.loadingScreen;
if (loadingScreen) {
loadingScreen.displayLoadingUI();
}
};
Engine2.prototype.hideLoadingUI = function() {
if (!BABYLON2.Tools.IsWindowObjectExist()) {
return;
}
var loadingScreen = this.loadingScreen;
if (loadingScreen) {
loadingScreen.hideLoadingUI();
}
};
Object.defineProperty(Engine2.prototype, "loadingScreen", {
/**
* Gets the current loading screen object
* @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
get: function() {
if (!this._loadingScreen && BABYLON2.DefaultLoadingScreen && this._renderingCanvas) {
this._loadingScreen = new BABYLON2.DefaultLoadingScreen(this._renderingCanvas);
}
return this._loadingScreen;
},
/**
* Sets the current loading screen object
* @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
set: function(loadingScreen) {
this._loadingScreen = loadingScreen;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "loadingUIText", {
/**
* Sets the current loading screen text
* @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
set: function(text) {
this.loadingScreen.loadingUIText = text;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Engine2.prototype, "loadingUIBackgroundColor", {
/**
* Sets the current loading screen background color
* @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
set: function(color) {
this.loadingScreen.loadingUIBackgroundColor = color;
},
enumerable: true,
configurable: true
});
Engine2.prototype.attachContextLostEvent = function(callback) {
if (this._renderingCanvas) {
this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
}
};
Engine2.prototype.attachContextRestoredEvent = function(callback) {
if (this._renderingCanvas) {
this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
}
};
Engine2.prototype.getVertexShaderSource = function(program) {
var shaders = this._gl.getAttachedShaders(program);
if (!shaders) {
return null;
}
return this._gl.getShaderSource(shaders[0]);
};
Engine2.prototype.getFragmentShaderSource = function(program) {
var shaders = this._gl.getAttachedShaders(program);
if (!shaders) {
return null;
}
return this._gl.getShaderSource(shaders[1]);
};
Engine2.prototype.getError = function() {
return this._gl.getError();
};
Engine2.prototype.getFps = function() {
return this._fps;
};
Engine2.prototype.getDeltaTime = function() {
return this._deltaTime;
};
Engine2.prototype._measureFps = function() {
this._performanceMonitor.sampleFrame();
this._fps = this._performanceMonitor.averageFPS;
this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
};
Engine2.prototype._readTexturePixels = function(texture, width, height, faceIndex, level, buffer) {
if (faceIndex === void 0) {
faceIndex = -1;
}
if (level === void 0) {
level = 0;
}
if (buffer === void 0) {
buffer = null;
}
var gl = this._gl;
if (!this._dummyFramebuffer) {
var dummy = gl.createFramebuffer();
if (!dummy) {
throw new Error("Unable to create dummy framebuffer");
}
this._dummyFramebuffer = dummy;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
if (faceIndex > -1) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
} else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
}
var readType = texture.type !== void 0 ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
switch (readType) {
case gl.UNSIGNED_BYTE:
if (!buffer) {
buffer = new Uint8Array(4 * width * height);
}
readType = gl.UNSIGNED_BYTE;
break;
default:
if (!buffer) {
buffer = new Float32Array(4 * width * height);
}
readType = gl.FLOAT;
break;
}
gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
return buffer;
};
Engine2.prototype._canRenderToFloatFramebuffer = function() {
if (this._webGLVersion > 1) {
return this._caps.colorBufferFloat;
}
return this._canRenderToFramebuffer(Engine2.TEXTURETYPE_FLOAT);
};
Engine2.prototype._canRenderToHalfFloatFramebuffer = function() {
if (this._webGLVersion > 1) {
return this._caps.colorBufferFloat;
}
return this._canRenderToFramebuffer(Engine2.TEXTURETYPE_HALF_FLOAT);
};
Engine2.prototype._canRenderToFramebuffer = function(type) {
var gl = this._gl;
while (gl.getError() !== gl.NO_ERROR) {
}
var successful = true;
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
successful = successful && status === gl.FRAMEBUFFER_COMPLETE;
successful = successful && gl.getError() === gl.NO_ERROR;
if (successful) {
gl.clear(gl.COLOR_BUFFER_BIT);
successful = successful && gl.getError() === gl.NO_ERROR;
}
if (successful) {
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var readFormat = gl.RGBA;
var readType = gl.UNSIGNED_BYTE;
var buffer = new Uint8Array(4);
gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
successful = successful && gl.getError() === gl.NO_ERROR;
}
gl.deleteTexture(texture);
gl.deleteFramebuffer(fb);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
while (!successful && gl.getError() !== gl.NO_ERROR) {
}
return successful;
};
Engine2.prototype._getWebGLTextureType = function(type) {
if (this._webGLVersion === 1) {
switch (type) {
case Engine2.TEXTURETYPE_FLOAT:
return this._gl.FLOAT;
case Engine2.TEXTURETYPE_HALF_FLOAT:
return this._gl.HALF_FLOAT_OES;
case Engine2.TEXTURETYPE_UNSIGNED_BYTE:
return this._gl.UNSIGNED_BYTE;
}
return this._gl.UNSIGNED_BYTE;
}
switch (type) {
case Engine2.TEXTURETYPE_BYTE:
return this._gl.BYTE;
case Engine2.TEXTURETYPE_UNSIGNED_BYTE:
return this._gl.UNSIGNED_BYTE;
case Engine2.TEXTURETYPE_SHORT:
return this._gl.SHORT;
case Engine2.TEXTURETYPE_UNSIGNED_SHORT:
return this._gl.UNSIGNED_SHORT;
case Engine2.TEXTURETYPE_INT:
return this._gl.INT;
case Engine2.TEXTURETYPE_UNSIGNED_INTEGER:
return this._gl.UNSIGNED_INT;
case Engine2.TEXTURETYPE_FLOAT:
return this._gl.FLOAT;
case Engine2.TEXTURETYPE_HALF_FLOAT:
return this._gl.HALF_FLOAT;
case Engine2.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
return this._gl.UNSIGNED_SHORT_4_4_4_4;
case Engine2.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
return this._gl.UNSIGNED_SHORT_5_5_5_1;
case Engine2.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
return this._gl.UNSIGNED_SHORT_5_6_5;
case Engine2.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
return this._gl.UNSIGNED_INT_2_10_10_10_REV;
case Engine2.TEXTURETYPE_UNSIGNED_INT_24_8:
return this._gl.UNSIGNED_INT_24_8;
case Engine2.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
case Engine2.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
return this._gl.UNSIGNED_INT_5_9_9_9_REV;
case Engine2.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
}
return this._gl.UNSIGNED_BYTE;
};
Engine2.prototype._getInternalFormat = function(format) {
var internalFormat = this._gl.RGBA;
switch (format) {
case Engine2.TEXTUREFORMAT_ALPHA:
internalFormat = this._gl.ALPHA;
break;
case Engine2.TEXTUREFORMAT_LUMINANCE:
internalFormat = this._gl.LUMINANCE;
break;
case Engine2.TEXTUREFORMAT_LUMINANCE_ALPHA:
internalFormat = this._gl.LUMINANCE_ALPHA;
break;
case Engine2.TEXTUREFORMAT_RED:
internalFormat = this._gl.RED;
break;
case Engine2.TEXTUREFORMAT_RG:
internalFormat = this._gl.RG;
break;
case Engine2.TEXTUREFORMAT_RGB:
internalFormat = this._gl.RGB;
break;
case Engine2.TEXTUREFORMAT_RGBA:
internalFormat = this._gl.RGBA;
break;
}
if (this._webGLVersion > 1) {
switch (format) {
case Engine2.TEXTUREFORMAT_RED_INTEGER:
internalFormat = this._gl.RED_INTEGER;
break;
case Engine2.TEXTUREFORMAT_RG_INTEGER:
internalFormat = this._gl.RG_INTEGER;
break;
case Engine2.TEXTUREFORMAT_RGB_INTEGER:
internalFormat = this._gl.RGB_INTEGER;
break;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
internalFormat = this._gl.RGBA_INTEGER;
break;
}
}
return internalFormat;
};
Engine2.prototype._getRGBABufferInternalSizedFormat = function(type, format) {
if (this._webGLVersion === 1) {
if (format !== void 0) {
switch (format) {
case Engine2.TEXTUREFORMAT_ALPHA:
return this._gl.ALPHA;
case Engine2.TEXTUREFORMAT_LUMINANCE:
return this._gl.LUMINANCE;
case Engine2.TEXTUREFORMAT_LUMINANCE_ALPHA:
return this._gl.LUMINANCE_ALPHA;
}
}
return this._gl.RGBA;
}
switch (type) {
case Engine2.TEXTURETYPE_BYTE:
switch (format) {
case Engine2.TEXTUREFORMAT_RED:
return this._gl.R8_SNORM;
case Engine2.TEXTUREFORMAT_RG:
return this._gl.RG8_SNORM;
case Engine2.TEXTUREFORMAT_RGB:
return this._gl.RGB8_SNORM;
case Engine2.TEXTUREFORMAT_RED_INTEGER:
return this._gl.R8I;
case Engine2.TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG8I;
case Engine2.TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB8I;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA8I;
default:
return this._gl.RGBA8_SNORM;
}
case Engine2.TEXTURETYPE_UNSIGNED_BYTE:
switch (format) {
case Engine2.TEXTUREFORMAT_RED:
return this._gl.R8;
case Engine2.TEXTUREFORMAT_RG:
return this._gl.RG8;
case Engine2.TEXTUREFORMAT_RGB:
return this._gl.RGB8;
case Engine2.TEXTUREFORMAT_RGBA:
return this._gl.RGBA8;
case Engine2.TEXTUREFORMAT_RED_INTEGER:
return this._gl.R8UI;
case Engine2.TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG8UI;
case Engine2.TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB8UI;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA8UI;
default:
return this._gl.RGBA8;
}
case Engine2.TEXTURETYPE_SHORT:
switch (format) {
case Engine2.TEXTUREFORMAT_RED_INTEGER:
return this._gl.R16I;
case Engine2.TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG16I;
case Engine2.TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB16I;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA16I;
default:
return this._gl.RGBA16I;
}
case Engine2.TEXTURETYPE_UNSIGNED_SHORT:
switch (format) {
case Engine2.TEXTUREFORMAT_RED_INTEGER:
return this._gl.R16UI;
case Engine2.TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG16UI;
case Engine2.TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB16UI;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA16UI;
default:
return this._gl.RGBA16UI;
}
case Engine2.TEXTURETYPE_INT:
switch (format) {
case Engine2.TEXTUREFORMAT_RED_INTEGER:
return this._gl.R32I;
case Engine2.TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG32I;
case Engine2.TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB32I;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA32I;
default:
return this._gl.RGBA32I;
}
case Engine2.TEXTURETYPE_UNSIGNED_INTEGER:
switch (format) {
case Engine2.TEXTUREFORMAT_RED_INTEGER:
return this._gl.R32UI;
case Engine2.TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG32UI;
case Engine2.TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB32UI;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA32UI;
default:
return this._gl.RGBA32UI;
}
case Engine2.TEXTURETYPE_FLOAT:
switch (format) {
case Engine2.TEXTUREFORMAT_RED:
return this._gl.R32F;
case Engine2.TEXTUREFORMAT_RG:
return this._gl.RG32F;
case Engine2.TEXTUREFORMAT_RGB:
return this._gl.RGB32F;
case Engine2.TEXTUREFORMAT_RGBA:
return this._gl.RGBA32F;
default:
return this._gl.RGBA32F;
}
case Engine2.TEXTURETYPE_HALF_FLOAT:
switch (format) {
case Engine2.TEXTUREFORMAT_RED:
return this._gl.R16F;
case Engine2.TEXTUREFORMAT_RG:
return this._gl.RG16F;
case Engine2.TEXTUREFORMAT_RGB:
return this._gl.RGB16F;
case Engine2.TEXTUREFORMAT_RGBA:
return this._gl.RGBA16F;
default:
return this._gl.RGBA16F;
}
case Engine2.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
return this._gl.RGB565;
case Engine2.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
return this._gl.R11F_G11F_B10F;
case Engine2.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
return this._gl.RGB9_E5;
case Engine2.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
return this._gl.RGBA4;
case Engine2.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
return this._gl.RGB5_A1;
case Engine2.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
switch (format) {
case Engine2.TEXTUREFORMAT_RGBA:
return this._gl.RGB10_A2;
case Engine2.TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGB10_A2UI;
default:
return this._gl.RGB10_A2;
}
}
return this._gl.RGBA8;
};
Engine2.prototype._getRGBAMultiSampleBufferFormat = function(type) {
if (type === Engine2.TEXTURETYPE_FLOAT) {
return this._gl.RGBA32F;
} else if (type === Engine2.TEXTURETYPE_HALF_FLOAT) {
return this._gl.RGBA16F;
}
return this._gl.RGBA8;
};
Engine2.prototype._loadFile = function(url, onSuccess, onProgress, database, useArrayBuffer, onError) {
var _this = this;
var request = BABYLON2.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
this._activeRequests.push(request);
request.onCompleteObservable.add(function(request2) {
_this._activeRequests.splice(_this._activeRequests.indexOf(request2), 1);
});
return request;
};
Engine2.prototype._loadFileAsync = function(url, database, useArrayBuffer) {
var _this = this;
return new Promise(function(resolve, reject) {
_this._loadFile(url, function(data2) {
resolve(data2);
}, void 0, database, useArrayBuffer, function(request, exception) {
reject(exception);
});
});
};
Engine2.prototype._partialLoadFile = function(url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
if (onErrorCallBack === void 0) {
onErrorCallBack = null;
}
var onload = function(data2) {
loadedFiles[index] = data2;
loadedFiles._internalCount++;
if (loadedFiles._internalCount === 6) {
onfinish(loadedFiles);
}
};
var onerror = function(request, exception) {
if (onErrorCallBack && request) {
onErrorCallBack(request.status + " " + request.statusText, exception);
}
};
this._loadFile(url, onload, void 0, void 0, true, onerror);
};
Engine2.prototype._cascadeLoadFiles = function(scene, onfinish, files, onError) {
if (onError === void 0) {
onError = null;
}
var loadedFiles = [];
loadedFiles._internalCount = 0;
for (var index = 0; index < 6; index++) {
this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
}
};
Engine2.isSupported = function() {
try {
var tempcanvas = document.createElement("canvas");
var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
return gl != null && !!window.WebGLRenderingContext;
} catch (e2) {
return false;
}
};
Engine2.ExceptionList = [
{ key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
{ key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
{ key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
{ key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
{ key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
{ key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
];
Engine2.Instances = new Array();
Engine2._TextureLoaders = [];
Engine2.ALPHA_DISABLE = 0;
Engine2.ALPHA_ADD = 1;
Engine2.ALPHA_COMBINE = 2;
Engine2.ALPHA_SUBTRACT = 3;
Engine2.ALPHA_MULTIPLY = 4;
Engine2.ALPHA_MAXIMIZED = 5;
Engine2.ALPHA_ONEONE = 6;
Engine2.ALPHA_PREMULTIPLIED = 7;
Engine2.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
Engine2.ALPHA_INTERPOLATE = 9;
Engine2.ALPHA_SCREENMODE = 10;
Engine2.DELAYLOADSTATE_NONE = 0;
Engine2.DELAYLOADSTATE_LOADED = 1;
Engine2.DELAYLOADSTATE_LOADING = 2;
Engine2.DELAYLOADSTATE_NOTLOADED = 4;
Engine2.NEVER = 512;
Engine2.ALWAYS = 519;
Engine2.LESS = 513;
Engine2.EQUAL = 514;
Engine2.LEQUAL = 515;
Engine2.GREATER = 516;
Engine2.GEQUAL = 518;
Engine2.NOTEQUAL = 517;
Engine2.KEEP = 7680;
Engine2.REPLACE = 7681;
Engine2.INCR = 7682;
Engine2.DECR = 7683;
Engine2.INVERT = 5386;
Engine2.INCR_WRAP = 34055;
Engine2.DECR_WRAP = 34056;
Engine2.TEXTURE_CLAMP_ADDRESSMODE = 0;
Engine2.TEXTURE_WRAP_ADDRESSMODE = 1;
Engine2.TEXTURE_MIRROR_ADDRESSMODE = 2;
Engine2.TEXTUREFORMAT_ALPHA = 0;
Engine2.TEXTUREFORMAT_LUMINANCE = 1;
Engine2.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
Engine2.TEXTUREFORMAT_RGB = 4;
Engine2.TEXTUREFORMAT_RGBA = 5;
Engine2.TEXTUREFORMAT_RED = 6;
Engine2.TEXTUREFORMAT_R = 6;
Engine2.TEXTUREFORMAT_RG = 7;
Engine2.TEXTUREFORMAT_RED_INTEGER = 8;
Engine2.TEXTUREFORMAT_R_INTEGER = 8;
Engine2.TEXTUREFORMAT_RG_INTEGER = 9;
Engine2.TEXTUREFORMAT_RGB_INTEGER = 10;
Engine2.TEXTUREFORMAT_RGBA_INTEGER = 11;
Engine2.TEXTURETYPE_UNSIGNED_BYTE = 0;
Engine2.TEXTURETYPE_UNSIGNED_INT = 0;
Engine2.TEXTURETYPE_FLOAT = 1;
Engine2.TEXTURETYPE_HALF_FLOAT = 2;
Engine2.TEXTURETYPE_BYTE = 3;
Engine2.TEXTURETYPE_SHORT = 4;
Engine2.TEXTURETYPE_UNSIGNED_SHORT = 5;
Engine2.TEXTURETYPE_INT = 6;
Engine2.TEXTURETYPE_UNSIGNED_INTEGER = 7;
Engine2.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
Engine2.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
Engine2.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
Engine2.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
Engine2.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
Engine2.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
Engine2.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
Engine2.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
Engine2.TEXTURE_NEAREST_SAMPLINGMODE = 1;
Engine2.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
Engine2.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
Engine2.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
Engine2.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
Engine2.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
Engine2.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
Engine2.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
Engine2.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
Engine2.TEXTURE_NEAREST_LINEAR = 7;
Engine2.TEXTURE_NEAREST_NEAREST = 8;
Engine2.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
Engine2.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
Engine2.TEXTURE_LINEAR_LINEAR = 11;
Engine2.TEXTURE_LINEAR_NEAREST = 12;
Engine2.TEXTURE_EXPLICIT_MODE = 0;
Engine2.TEXTURE_SPHERICAL_MODE = 1;
Engine2.TEXTURE_PLANAR_MODE = 2;
Engine2.TEXTURE_CUBIC_MODE = 3;
Engine2.TEXTURE_PROJECTION_MODE = 4;
Engine2.TEXTURE_SKYBOX_MODE = 5;
Engine2.TEXTURE_INVCUBIC_MODE = 6;
Engine2.TEXTURE_EQUIRECTANGULAR_MODE = 7;
Engine2.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
Engine2.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
Engine2.SCALEMODE_FLOOR = 1;
Engine2.SCALEMODE_NEAREST = 2;
Engine2.SCALEMODE_CEILING = 3;
Engine2.CollisionsEpsilon = 1e-3;
Engine2.CodeRepository = "src/";
Engine2.ShadersRepository = "src/Shaders/";
return Engine2;
}()
);
BABYLON2.Engine = Engine;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Node = (
/** @class */
function() {
function Node2(name, scene) {
if (scene === void 0) {
scene = null;
}
this.state = "";
this.metadata = null;
this.doNotSerialize = false;
this._isDisposed = false;
this.animations = new Array();
this._ranges = {};
this._isEnabled = true;
this._isParentEnabled = true;
this._isReady = true;
this._currentRenderId = -1;
this._parentRenderId = -1;
this._childRenderId = -1;
this._worldMatrix = BABYLON2.Matrix.Identity();
this._worldMatrixDeterminant = 0;
this._sceneRootNodesIndex = -1;
this._animationPropertiesOverride = null;
this.onDisposeObservable = new BABYLON2.Observable();
this._behaviors = new Array();
this.name = name;
this.id = name;
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
this.uniqueId = this._scene.getUniqueId();
this._initCache();
this.addToSceneRootNodes();
}
Node2.AddNodeConstructor = function(type, constructorFunc) {
this._NodeConstructors[type] = constructorFunc;
};
Node2.Construct = function(type, name, scene, options) {
var constructorFunc = this._NodeConstructors[type];
if (!constructorFunc) {
return null;
}
return constructorFunc(name, scene, options);
};
Node2.prototype.isDisposed = function() {
return this._isDisposed;
};
Object.defineProperty(Node2.prototype, "parent", {
get: function() {
return this._parentNode;
},
/**
* Gets or sets the parent of the node
*/
set: function(parent) {
if (this._parentNode === parent) {
return;
}
var previousParentNode = this._parentNode;
if (this._parentNode && this._parentNode._children !== void 0 && this._parentNode._children !== null) {
var index = this._parentNode._children.indexOf(this);
if (index !== -1) {
this._parentNode._children.splice(index, 1);
}
if (!parent) {
this.addToSceneRootNodes();
}
}
this._parentNode = parent;
if (this._parentNode) {
if (this._parentNode._children === void 0 || this._parentNode._children === null) {
this._parentNode._children = new Array();
}
this._parentNode._children.push(this);
if (!previousParentNode) {
this.removeFromSceneRootNodes();
}
}
this._syncParentEnabledState();
},
enumerable: true,
configurable: true
});
Node2.prototype.addToSceneRootNodes = function() {
if (this._sceneRootNodesIndex === -1) {
this._sceneRootNodesIndex = this._scene.rootNodes.length;
this._scene.rootNodes.push(this);
}
};
Node2.prototype.removeFromSceneRootNodes = function() {
if (this._sceneRootNodesIndex !== -1) {
var rootNodes = this._scene.rootNodes;
var lastIdx = rootNodes.length - 1;
rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
this._scene.rootNodes.pop();
this._sceneRootNodesIndex = -1;
}
};
Object.defineProperty(Node2.prototype, "animationPropertiesOverride", {
/**
* Gets or sets the animation properties override
*/
get: function() {
if (!this._animationPropertiesOverride) {
return this._scene.animationPropertiesOverride;
}
return this._animationPropertiesOverride;
},
set: function(value) {
this._animationPropertiesOverride = value;
},
enumerable: true,
configurable: true
});
Node2.prototype.getClassName = function() {
return "Node";
};
Object.defineProperty(Node2.prototype, "onDispose", {
/**
* Sets a callback that will be raised when the node will be disposed
*/
set: function(callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Node2.prototype.getScene = function() {
return this._scene;
};
Node2.prototype.getEngine = function() {
return this._scene.getEngine();
};
Node2.prototype.addBehavior = function(behavior, attachImmediately) {
var _this = this;
if (attachImmediately === void 0) {
attachImmediately = false;
}
var index = this._behaviors.indexOf(behavior);
if (index !== -1) {
return this;
}
behavior.init();
if (this._scene.isLoading && !attachImmediately) {
this._scene.onDataLoadedObservable.addOnce(function() {
behavior.attach(_this);
});
} else {
behavior.attach(this);
}
this._behaviors.push(behavior);
return this;
};
Node2.prototype.removeBehavior = function(behavior) {
var index = this._behaviors.indexOf(behavior);
if (index === -1) {
return this;
}
this._behaviors[index].detach();
this._behaviors.splice(index, 1);
return this;
};
Object.defineProperty(Node2.prototype, "behaviors", {
/**
* Gets the list of attached behaviors
* @see http://doc.babylonjs.com/features/behaviour
*/
get: function() {
return this._behaviors;
},
enumerable: true,
configurable: true
});
Node2.prototype.getBehaviorByName = function(name) {
for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
var behavior = _a[_i];
if (behavior.name === name) {
return behavior;
}
}
return null;
};
Node2.prototype.getWorldMatrix = function() {
if (this._currentRenderId !== this._scene.getRenderId()) {
this.computeWorldMatrix();
}
return this._worldMatrix;
};
Node2.prototype._getWorldMatrixDeterminant = function() {
return this._worldMatrixDeterminant;
};
Object.defineProperty(Node2.prototype, "worldMatrixFromCache", {
/**
* Returns directly the latest state of the mesh World matrix.
* A Matrix is returned.
*/
get: function() {
return this._worldMatrix;
},
enumerable: true,
configurable: true
});
Node2.prototype._initCache = function() {
this._cache = {};
this._cache.parent = void 0;
};
Node2.prototype.updateCache = function(force) {
if (!force && this.isSynchronized()) {
return;
}
this._cache.parent = this.parent;
this._updateCache();
};
Node2.prototype._updateCache = function(ignoreParentClass) {
};
Node2.prototype._isSynchronized = function() {
return true;
};
Node2.prototype._markSyncedWithParent = function() {
if (this._parentNode) {
this._parentRenderId = this._parentNode._childRenderId;
}
};
Node2.prototype.isSynchronizedWithParent = function() {
if (!this._parentNode) {
return true;
}
if (this._parentRenderId !== this._parentNode._childRenderId) {
return false;
}
return this._parentNode.isSynchronized();
};
Node2.prototype.isSynchronized = function() {
if (this._cache.parent != this._parentNode) {
this._cache.parent = this._parentNode;
return false;
}
if (this._parentNode && !this.isSynchronizedWithParent()) {
return false;
}
return this._isSynchronized();
};
Node2.prototype.isReady = function(completeCheck) {
if (completeCheck === void 0) {
completeCheck = false;
}
return this._isReady;
};
Node2.prototype.isEnabled = function(checkAncestors) {
if (checkAncestors === void 0) {
checkAncestors = true;
}
if (checkAncestors === false) {
return this._isEnabled;
}
if (!this._isEnabled) {
return false;
}
return this._isParentEnabled;
};
Node2.prototype._syncParentEnabledState = function() {
this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
if (this._children) {
this._children.forEach(function(c) {
c._syncParentEnabledState();
});
}
};
Node2.prototype.setEnabled = function(value) {
this._isEnabled = value;
this._syncParentEnabledState();
};
Node2.prototype.isDescendantOf = function(ancestor) {
if (this.parent) {
if (this.parent === ancestor) {
return true;
}
return this.parent.isDescendantOf(ancestor);
}
return false;
};
Node2.prototype._getDescendants = function(results, directDescendantsOnly, predicate) {
if (directDescendantsOnly === void 0) {
directDescendantsOnly = false;
}
if (!this._children) {
return;
}
for (var index = 0; index < this._children.length; index++) {
var item = this._children[index];
if (!predicate || predicate(item)) {
results.push(item);
}
if (!directDescendantsOnly) {
item._getDescendants(results, false, predicate);
}
}
};
Node2.prototype.getDescendants = function(directDescendantsOnly, predicate) {
var results = new Array();
this._getDescendants(results, directDescendantsOnly, predicate);
return results;
};
Node2.prototype.getChildMeshes = function(directDescendantsOnly, predicate) {
var results = [];
this._getDescendants(results, directDescendantsOnly, function(node) {
return (!predicate || predicate(node)) && node instanceof BABYLON2.AbstractMesh;
});
return results;
};
Node2.prototype.getChildTransformNodes = function(directDescendantsOnly, predicate) {
var results = [];
this._getDescendants(results, directDescendantsOnly, function(node) {
return (!predicate || predicate(node)) && node instanceof BABYLON2.TransformNode;
});
return results;
};
Node2.prototype.getChildren = function(predicate) {
return this.getDescendants(true, predicate);
};
Node2.prototype._setReady = function(state) {
if (state === this._isReady) {
return;
}
if (!state) {
this._isReady = false;
return;
}
if (this.onReady) {
this.onReady(this);
}
this._isReady = true;
};
Node2.prototype.getAnimationByName = function(name) {
for (var i2 = 0; i2 < this.animations.length; i2++) {
var animation = this.animations[i2];
if (animation.name === name) {
return animation;
}
}
return null;
};
Node2.prototype.createAnimationRange = function(name, from, to) {
if (!this._ranges[name]) {
this._ranges[name] = new BABYLON2.AnimationRange(name, from, to);
for (var i2 = 0, nAnimations = this.animations.length; i2 < nAnimations; i2++) {
if (this.animations[i2]) {
this.animations[i2].createRange(name, from, to);
}
}
}
};
Node2.prototype.deleteAnimationRange = function(name, deleteFrames) {
if (deleteFrames === void 0) {
deleteFrames = true;
}
for (var i2 = 0, nAnimations = this.animations.length; i2 < nAnimations; i2++) {
if (this.animations[i2]) {
this.animations[i2].deleteRange(name, deleteFrames);
}
}
this._ranges[name] = null;
};
Node2.prototype.getAnimationRange = function(name) {
return this._ranges[name];
};
Node2.prototype.beginAnimation = function(name, loop, speedRatio, onAnimationEnd) {
var range = this.getAnimationRange(name);
if (!range) {
return null;
}
return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
};
Node2.prototype.serializeAnimationRanges = function() {
var serializationRanges = [];
for (var name in this._ranges) {
var localRange = this._ranges[name];
if (!localRange) {
continue;
}
var range = {};
range.name = name;
range.from = localRange.from;
range.to = localRange.to;
serializationRanges.push(range);
}
return serializationRanges;
};
Node2.prototype.computeWorldMatrix = function(force) {
if (!this._worldMatrix) {
this._worldMatrix = BABYLON2.Matrix.Identity();
}
return this._worldMatrix;
};
Node2.prototype.dispose = function(doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) {
disposeMaterialAndTextures = false;
}
if (!doNotRecurse) {
var nodes = this.getDescendants(true);
for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
var node = nodes_1[_i];
node.dispose(doNotRecurse, disposeMaterialAndTextures);
}
} else {
var transformNodes = this.getChildTransformNodes(true);
for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
var transformNode = transformNodes_1[_a];
transformNode.parent = null;
transformNode.computeWorldMatrix(true);
}
}
if (!this.parent) {
this.removeFromSceneRootNodes();
} else {
this.parent = null;
}
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
var behavior = _c[_b];
behavior.detach();
}
this._behaviors = [];
this._isDisposed = true;
};
Node2.ParseAnimationRanges = function(node, parsedNode, scene) {
if (parsedNode.ranges) {
for (var index = 0; index < parsedNode.ranges.length; index++) {
var data2 = parsedNode.ranges[index];
node.createAnimationRange(data2.name, data2.from, data2.to);
}
}
};
Node2._NodeConstructors = {};
__decorate([
BABYLON2.serialize()
], Node2.prototype, "name", void 0);
__decorate([
BABYLON2.serialize()
], Node2.prototype, "id", void 0);
__decorate([
BABYLON2.serialize()
], Node2.prototype, "uniqueId", void 0);
__decorate([
BABYLON2.serialize()
], Node2.prototype, "state", void 0);
__decorate([
BABYLON2.serialize()
], Node2.prototype, "metadata", void 0);
return Node2;
}()
);
BABYLON2.Node = Node;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _identityMatrix = BABYLON2.Matrix.Identity();
var BoundingSphere = (
/** @class */
function() {
function BoundingSphere2(min, max) {
this.center = BABYLON2.Vector3.Zero();
this.centerWorld = BABYLON2.Vector3.Zero();
this.minimum = BABYLON2.Vector3.Zero();
this.maximum = BABYLON2.Vector3.Zero();
this.reConstruct(min, max);
}
BoundingSphere2.prototype.reConstruct = function(min, max) {
this.minimum.copyFrom(min);
this.maximum.copyFrom(max);
var distance = BABYLON2.Vector3.Distance(min, max);
BABYLON2.Vector3.LerpToRef(min, max, 0.5, this.center);
this.radius = distance * 0.5;
this.centerWorld.set(0, 0, 0);
this._update(_identityMatrix);
};
BoundingSphere2.prototype.scale = function(factor) {
var newRadius = this.radius * factor;
var tempRadiusVector = BABYLON2.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
var min = BABYLON2.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
var max = BABYLON2.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
this.reConstruct(min, max);
return this;
};
BoundingSphere2.prototype._update = function(world) {
BABYLON2.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
var tempVector = BABYLON2.Tmp.Vector3[0];
BABYLON2.Vector3.TransformNormalFromFloatsToRef(1, 1, 1, world, tempVector);
this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
};
BoundingSphere2.prototype.isInFrustum = function(frustumPlanes) {
for (var i2 = 0; i2 < 6; i2++) {
if (frustumPlanes[i2].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
return false;
}
}
return true;
};
BoundingSphere2.prototype.intersectsPoint = function(point) {
var x = this.centerWorld.x - point.x;
var y = this.centerWorld.y - point.y;
var z = this.centerWorld.z - point.z;
var distance = Math.sqrt(x * x + y * y + z * z);
if (this.radiusWorld < distance) {
return false;
}
return true;
};
BoundingSphere2.Intersects = function(sphere0, sphere1) {
var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
var distance = Math.sqrt(x * x + y * y + z * z);
if (sphere0.radiusWorld + sphere1.radiusWorld < distance) {
return false;
}
return true;
};
return BoundingSphere2;
}()
);
BABYLON2.BoundingSphere = BoundingSphere;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BoundingBox = (
/** @class */
function() {
function BoundingBox2(min, max) {
this.vectors = [BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero()];
this.center = BABYLON2.Vector3.Zero();
this.centerWorld = BABYLON2.Vector3.Zero();
this.extendSize = BABYLON2.Vector3.Zero();
this.extendSizeWorld = BABYLON2.Vector3.Zero();
this.directions = [BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero()];
this.vectorsWorld = [BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero()];
this.minimumWorld = BABYLON2.Vector3.Zero();
this.maximumWorld = BABYLON2.Vector3.Zero();
this.minimum = BABYLON2.Vector3.Zero();
this.maximum = BABYLON2.Vector3.Zero();
this.reConstruct(min, max);
}
BoundingBox2.prototype.reConstruct = function(min, max) {
this.minimum.copyFrom(min);
this.maximum.copyFrom(max);
this.vectors[0].copyFrom(this.minimum);
this.vectors[1].copyFrom(this.maximum);
this.vectors[2].copyFrom(this.minimum);
this.vectors[3].copyFrom(this.minimum);
this.vectors[4].copyFrom(this.minimum);
this.vectors[5].copyFrom(this.maximum);
this.vectors[6].copyFrom(this.maximum);
this.vectors[7].copyFrom(this.maximum);
this.vectors[2].x = this.maximum.x;
this.vectors[3].y = this.maximum.y;
this.vectors[4].z = this.maximum.z;
this.vectors[5].z = this.minimum.z;
this.vectors[6].x = this.minimum.x;
this.vectors[7].y = this.minimum.y;
this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
for (var index = 0; index < 3; index++) {
this.directions[index].copyFromFloats(0, 0, 0);
}
for (var index = 0; index < 8; index++) {
this.vectorsWorld[index].copyFromFloats(0, 0, 0);
}
this.minimumWorld.copyFromFloats(0, 0, 0);
this.maximumWorld.copyFromFloats(0, 0, 0);
this.centerWorld.copyFromFloats(0, 0, 0);
this.extendSizeWorld.copyFromFloats(0, 0, 0);
this._update(this._worldMatrix || BABYLON2.Matrix.Identity());
};
BoundingBox2.prototype.scale = function(factor) {
var diff = BABYLON2.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
var distance = diff.length() * factor;
diff.normalize();
var newRadius = diff.scaleInPlace(distance * 0.5);
var min = BABYLON2.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
var max = BABYLON2.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
this.reConstruct(min, max);
return this;
};
BoundingBox2.prototype.getWorldMatrix = function() {
return this._worldMatrix;
};
BoundingBox2.prototype.setWorldMatrix = function(matrix) {
this._worldMatrix.copyFrom(matrix);
return this;
};
BoundingBox2.prototype._update = function(world) {
BABYLON2.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
BABYLON2.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
for (var index = 0; index < 8; index++) {
var v = this.vectorsWorld[index];
BABYLON2.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
this.minimumWorld.minimizeInPlace(v);
this.maximumWorld.maximizeInPlace(v);
}
this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
this.extendSizeWorld.scaleInPlace(0.5);
this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
this.centerWorld.scaleInPlace(0.5);
BABYLON2.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
BABYLON2.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
BABYLON2.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
this._worldMatrix = world;
};
BoundingBox2.prototype.isInFrustum = function(frustumPlanes) {
return BoundingBox2.IsInFrustum(this.vectorsWorld, frustumPlanes);
};
BoundingBox2.prototype.isCompletelyInFrustum = function(frustumPlanes) {
return BoundingBox2.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
};
BoundingBox2.prototype.intersectsPoint = function(point, useLocal) {
var min = useLocal ? this.minimum : this.minimumWorld;
var max = useLocal ? this.maximum : this.maximumWorld;
var delta = -BABYLON2.Epsilon;
if (max.x - point.x < delta || delta > point.x - min.x) {
return false;
}
if (max.y - point.y < delta || delta > point.y - min.y) {
return false;
}
if (max.z - point.z < delta || delta > point.z - min.z) {
return false;
}
return true;
};
BoundingBox2.prototype.intersectsSphere = function(sphere) {
return BoundingBox2.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
};
BoundingBox2.prototype.intersectsMinMax = function(min, max) {
if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x) {
return false;
}
if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y) {
return false;
}
if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z) {
return false;
}
return true;
};
BoundingBox2.Intersects = function(box0, box1) {
if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x) {
return false;
}
if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y) {
return false;
}
if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z) {
return false;
}
return true;
};
BoundingBox2.IntersectsSphere = function(minPoint, maxPoint, sphereCenter, sphereRadius) {
var vector = BABYLON2.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
var num = BABYLON2.Vector3.DistanceSquared(sphereCenter, vector);
return num <= sphereRadius * sphereRadius;
};
BoundingBox2.IsCompletelyInFrustum = function(boundingVectors, frustumPlanes) {
for (var p = 0; p < 6; p++) {
for (var i2 = 0; i2 < 8; i2++) {
if (frustumPlanes[p].dotCoordinate(boundingVectors[i2]) < 0) {
return false;
}
}
}
return true;
};
BoundingBox2.IsInFrustum = function(boundingVectors, frustumPlanes) {
for (var p = 0; p < 6; p++) {
var inCount = 8;
for (var i2 = 0; i2 < 8; i2++) {
if (frustumPlanes[p].dotCoordinate(boundingVectors[i2]) < 0) {
--inCount;
} else {
break;
}
}
if (inCount === 0) {
return false;
}
}
return true;
};
return BoundingBox2;
}()
);
BABYLON2.BoundingBox = BoundingBox;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var computeBoxExtents = function(axis, box) {
var p = BABYLON2.Vector3.Dot(box.centerWorld, axis);
var r0 = Math.abs(BABYLON2.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
var r1 = Math.abs(BABYLON2.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
var r2 = Math.abs(BABYLON2.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
var r = r0 + r1 + r2;
return {
min: p - r,
max: p + r
};
};
var extentsOverlap = function(min0, max0, min1, max1) {
return !(min0 > max1 || min1 > max0);
};
var axisOverlap = function(axis, box0, box1) {
var result0 = computeBoxExtents(axis, box0);
var result1 = computeBoxExtents(axis, box1);
return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
};
var BoundingInfo = (
/** @class */
function() {
function BoundingInfo2(minimum, maximum) {
this._isLocked = false;
this.boundingBox = new BABYLON2.BoundingBox(minimum, maximum);
this.boundingSphere = new BABYLON2.BoundingSphere(minimum, maximum);
}
Object.defineProperty(BoundingInfo2.prototype, "minimum", {
/**
* min vector of the bounding box/sphere
*/
get: function() {
return this.boundingBox.minimum;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BoundingInfo2.prototype, "maximum", {
/**
* max vector of the bounding box/sphere
*/
get: function() {
return this.boundingBox.maximum;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BoundingInfo2.prototype, "isLocked", {
/**
* If the info is locked and won't be updated to avoid perf overhead
*/
get: function() {
return this._isLocked;
},
set: function(value) {
this._isLocked = value;
},
enumerable: true,
configurable: true
});
BoundingInfo2.prototype.update = function(world) {
if (this._isLocked) {
return;
}
this.boundingBox._update(world);
this.boundingSphere._update(world);
};
BoundingInfo2.prototype.centerOn = function(center, extend) {
var minimum = BABYLON2.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
var maximum = BABYLON2.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
this.boundingBox.reConstruct(minimum, maximum);
this.boundingSphere.reConstruct(minimum, maximum);
return this;
};
BoundingInfo2.prototype.scale = function(factor) {
this.boundingBox.scale(factor);
this.boundingSphere.scale(factor);
return this;
};
BoundingInfo2.prototype.isInFrustum = function(frustumPlanes, strategy) {
if (strategy === void 0) {
strategy = BABYLON2.AbstractMesh.CULLINGSTRATEGY_STANDARD;
}
if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
return false;
}
if (strategy === BABYLON2.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
return true;
}
return this.boundingBox.isInFrustum(frustumPlanes);
};
Object.defineProperty(BoundingInfo2.prototype, "diagonalLength", {
/**
* Gets the world distance between the min and max points of the bounding box
*/
get: function() {
var boundingBox = this.boundingBox;
var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
return size.length();
},
enumerable: true,
configurable: true
});
BoundingInfo2.prototype.isCompletelyInFrustum = function(frustumPlanes) {
return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
};
BoundingInfo2.prototype._checkCollision = function(collider) {
return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
};
BoundingInfo2.prototype.intersectsPoint = function(point, useLocal) {
if (!this.boundingSphere.centerWorld) {
return false;
}
if (!this.boundingSphere.intersectsPoint(point)) {
return false;
}
if (!this.boundingBox.intersectsPoint(point, useLocal)) {
return false;
}
return true;
};
BoundingInfo2.prototype.intersects = function(boundingInfo, precise) {
if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
return false;
}
if (!BABYLON2.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
return false;
}
if (!BABYLON2.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
return false;
}
if (!precise) {
return true;
}
var box0 = this.boundingBox;
var box1 = boundingInfo.boundingBox;
if (!axisOverlap(box0.directions[0], box0, box1)) {
return false;
}
if (!axisOverlap(box0.directions[1], box0, box1)) {
return false;
}
if (!axisOverlap(box0.directions[2], box0, box1)) {
return false;
}
if (!axisOverlap(box1.directions[0], box0, box1)) {
return false;
}
if (!axisOverlap(box1.directions[1], box0, box1)) {
return false;
}
if (!axisOverlap(box1.directions[2], box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
return false;
}
if (!axisOverlap(BABYLON2.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
return false;
}
return true;
};
return BoundingInfo2;
}()
);
BABYLON2.BoundingInfo = BoundingInfo;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var TransformNode = (
/** @class */
function(_super) {
__extends(TransformNode2, _super);
function TransformNode2(name, scene, isPure) {
if (scene === void 0) {
scene = null;
}
if (isPure === void 0) {
isPure = true;
}
var _this = _super.call(this, name, scene) || this;
_this._forward = new BABYLON2.Vector3(0, 0, 1);
_this._forwardInverted = new BABYLON2.Vector3(0, 0, -1);
_this._up = new BABYLON2.Vector3(0, 1, 0);
_this._right = new BABYLON2.Vector3(1, 0, 0);
_this._rightInverted = new BABYLON2.Vector3(-1, 0, 0);
_this._position = BABYLON2.Vector3.Zero();
_this._rotation = BABYLON2.Vector3.Zero();
_this._scaling = BABYLON2.Vector3.One();
_this._isDirty = false;
_this.billboardMode = TransformNode2.BILLBOARDMODE_NONE;
_this.scalingDeterminant = 1;
_this.infiniteDistance = false;
_this.ignoreNonUniformScaling = false;
_this._localWorld = BABYLON2.Matrix.Zero();
_this._absolutePosition = BABYLON2.Vector3.Zero();
_this._pivotMatrix = BABYLON2.Matrix.Identity();
_this._postMultiplyPivotMatrix = false;
_this._isWorldMatrixFrozen = false;
_this.onAfterWorldMatrixUpdateObservable = new BABYLON2.Observable();
_this._nonUniformScaling = false;
if (isPure) {
_this.getScene().addTransformNode(_this);
}
return _this;
}
TransformNode2.prototype.getClassName = function() {
return "TransformNode";
};
Object.defineProperty(TransformNode2.prototype, "position", {
/**
* Gets or set the node position (default is (0.0, 0.0, 0.0))
*/
get: function() {
return this._position;
},
set: function(newPosition) {
this._position = newPosition;
this._isDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode2.prototype, "rotation", {
/**
* Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
* If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
*/
get: function() {
return this._rotation;
},
set: function(newRotation) {
this._rotation = newRotation;
this._isDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode2.prototype, "scaling", {
/**
* Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
*/
get: function() {
return this._scaling;
},
set: function(newScaling) {
this._scaling = newScaling;
this._isDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode2.prototype, "rotationQuaternion", {
/**
* Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
* If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
*/
get: function() {
return this._rotationQuaternion;
},
set: function(quaternion) {
this._rotationQuaternion = quaternion;
if (quaternion && this.rotation.length()) {
this.rotation.copyFromFloats(0, 0, 0);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode2.prototype, "forward", {
/**
* The forward direction of that transform in world space.
*/
get: function() {
return BABYLON2.Vector3.Normalize(BABYLON2.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode2.prototype, "up", {
/**
* The up direction of that transform in world space.
*/
get: function() {
return BABYLON2.Vector3.Normalize(BABYLON2.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
},
enumerable: true,
configurable: true
});
Object.defineProperty(TransformNode2.prototype, "right", {
/**
* The right direction of that transform in world space.
*/
get: function() {
return BABYLON2.Vector3.Normalize(BABYLON2.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
},
enumerable: true,
configurable: true
});
TransformNode2.prototype.updatePoseMatrix = function(matrix) {
this._poseMatrix.copyFrom(matrix);
return this;
};
TransformNode2.prototype.getPoseMatrix = function() {
return this._poseMatrix;
};
TransformNode2.prototype._isSynchronized = function() {
if (this._isDirty) {
return false;
}
if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode2.BILLBOARDMODE_NONE) {
return false;
}
if (this._cache.pivotMatrixUpdated) {
return false;
}
if (this.infiniteDistance) {
return false;
}
if (!this._cache.position.equals(this._position)) {
return false;
}
if (this._rotationQuaternion) {
if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
return false;
}
}
if (!this._cache.rotation.equals(this._rotation)) {
return false;
}
if (!this._cache.scaling.equals(this._scaling)) {
return false;
}
return true;
};
TransformNode2.prototype._initCache = function() {
_super.prototype._initCache.call(this);
this._cache.localMatrixUpdated = false;
this._cache.position = BABYLON2.Vector3.Zero();
this._cache.scaling = BABYLON2.Vector3.Zero();
this._cache.rotation = BABYLON2.Vector3.Zero();
this._cache.rotationQuaternion = new BABYLON2.Quaternion(0, 0, 0, 0);
this._cache.billboardMode = -1;
};
TransformNode2.prototype.markAsDirty = function(property) {
if (property === "rotation") {
this.rotationQuaternion = null;
}
this._currentRenderId = Number.MAX_VALUE;
this._isDirty = true;
return this;
};
Object.defineProperty(TransformNode2.prototype, "absolutePosition", {
/**
* Returns the current mesh absolute position.
* Returns a Vector3.
*/
get: function() {
return this._absolutePosition;
},
enumerable: true,
configurable: true
});
TransformNode2.prototype.setPreTransformMatrix = function(matrix) {
return this.setPivotMatrix(matrix, false);
};
TransformNode2.prototype.setPivotMatrix = function(matrix, postMultiplyPivotMatrix) {
if (postMultiplyPivotMatrix === void 0) {
postMultiplyPivotMatrix = true;
}
this._pivotMatrix = matrix.clone();
this._cache.pivotMatrixUpdated = true;
this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
if (this._postMultiplyPivotMatrix) {
if (!this._pivotMatrixInverse) {
this._pivotMatrixInverse = BABYLON2.Matrix.Invert(this._pivotMatrix);
} else {
this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
}
}
return this;
};
TransformNode2.prototype.getPivotMatrix = function() {
return this._pivotMatrix;
};
TransformNode2.prototype.freezeWorldMatrix = function() {
this._isWorldMatrixFrozen = false;
this.computeWorldMatrix(true);
this._isWorldMatrixFrozen = true;
return this;
};
TransformNode2.prototype.unfreezeWorldMatrix = function() {
this._isWorldMatrixFrozen = false;
this.computeWorldMatrix(true);
return this;
};
Object.defineProperty(TransformNode2.prototype, "isWorldMatrixFrozen", {
/**
* True if the World matrix has been frozen.
*/
get: function() {
return this._isWorldMatrixFrozen;
},
enumerable: true,
configurable: true
});
TransformNode2.prototype.getAbsolutePosition = function() {
this.computeWorldMatrix();
return this._absolutePosition;
};
TransformNode2.prototype.setAbsolutePosition = function(absolutePosition) {
if (!absolutePosition) {
return this;
}
var absolutePositionX;
var absolutePositionY;
var absolutePositionZ;
if (absolutePosition.x === void 0) {
if (arguments.length < 3) {
return this;
}
absolutePositionX = arguments[0];
absolutePositionY = arguments[1];
absolutePositionZ = arguments[2];
} else {
absolutePositionX = absolutePosition.x;
absolutePositionY = absolutePosition.y;
absolutePositionZ = absolutePosition.z;
}
if (this.parent) {
var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
invertParentWorldMatrix.invert();
var worldPosition = new BABYLON2.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
this.position = BABYLON2.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
} else {
this.position.x = absolutePositionX;
this.position.y = absolutePositionY;
this.position.z = absolutePositionZ;
}
return this;
};
TransformNode2.prototype.setPositionWithLocalVector = function(vector3) {
this.computeWorldMatrix();
this.position = BABYLON2.Vector3.TransformNormal(vector3, this._localWorld);
return this;
};
TransformNode2.prototype.getPositionExpressedInLocalSpace = function() {
this.computeWorldMatrix();
var invLocalWorldMatrix = this._localWorld.clone();
invLocalWorldMatrix.invert();
return BABYLON2.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
};
TransformNode2.prototype.locallyTranslate = function(vector3) {
this.computeWorldMatrix(true);
this.position = BABYLON2.Vector3.TransformCoordinates(vector3, this._localWorld);
return this;
};
TransformNode2.prototype.lookAt = function(targetPoint, yawCor, pitchCor, rollCor, space) {
if (yawCor === void 0) {
yawCor = 0;
}
if (pitchCor === void 0) {
pitchCor = 0;
}
if (rollCor === void 0) {
rollCor = 0;
}
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
var dv = TransformNode2._lookAtVectorCache;
var pos = space === BABYLON2.Space.LOCAL ? this.position : this.getAbsolutePosition();
targetPoint.subtractToRef(pos, dv);
var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
var pitch = Math.atan2(dv.y, len);
if (this.rotationQuaternion) {
BABYLON2.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
} else {
this.rotation.x = pitch + pitchCor;
this.rotation.y = yaw + yawCor;
this.rotation.z = rollCor;
}
return this;
};
TransformNode2.prototype.getDirection = function(localAxis) {
var result = BABYLON2.Vector3.Zero();
this.getDirectionToRef(localAxis, result);
return result;
};
TransformNode2.prototype.getDirectionToRef = function(localAxis, result) {
BABYLON2.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
return this;
};
TransformNode2.prototype.setPivotPoint = function(point, space) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (this.getScene().getRenderId() == 0) {
this.computeWorldMatrix(true);
}
var wm = this.getWorldMatrix();
if (space == BABYLON2.Space.WORLD) {
var tmat = BABYLON2.Tmp.Matrix[0];
wm.invertToRef(tmat);
point = BABYLON2.Vector3.TransformCoordinates(point, tmat);
}
return this.setPivotMatrix(BABYLON2.Matrix.Translation(-point.x, -point.y, -point.z), true);
};
TransformNode2.prototype.getPivotPoint = function() {
var point = BABYLON2.Vector3.Zero();
this.getPivotPointToRef(point);
return point;
};
TransformNode2.prototype.getPivotPointToRef = function(result) {
result.x = -this._pivotMatrix.m[12];
result.y = -this._pivotMatrix.m[13];
result.z = -this._pivotMatrix.m[14];
return this;
};
TransformNode2.prototype.getAbsolutePivotPoint = function() {
var point = BABYLON2.Vector3.Zero();
this.getAbsolutePivotPointToRef(point);
return point;
};
TransformNode2.prototype.getAbsolutePivotPointToRef = function(result) {
result.x = this._pivotMatrix.m[12];
result.y = this._pivotMatrix.m[13];
result.z = this._pivotMatrix.m[14];
this.getPivotPointToRef(result);
BABYLON2.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
return this;
};
TransformNode2.prototype.setParent = function(node) {
if (!node && !this.parent) {
return this;
}
if (!node) {
var rotation = BABYLON2.Tmp.Quaternion[0];
var position = BABYLON2.Tmp.Vector3[0];
var scale = BABYLON2.Tmp.Vector3[1];
if (this.parent && this.parent.computeWorldMatrix) {
this.parent.computeWorldMatrix(true);
}
this.computeWorldMatrix(true);
this.getWorldMatrix().decompose(scale, rotation, position);
if (this.rotationQuaternion) {
this.rotationQuaternion.copyFrom(rotation);
} else {
rotation.toEulerAnglesToRef(this.rotation);
}
this.scaling.x = scale.x;
this.scaling.y = scale.y;
this.scaling.z = scale.z;
this.position.x = position.x;
this.position.y = position.y;
this.position.z = position.z;
} else {
var rotation = BABYLON2.Tmp.Quaternion[0];
var position = BABYLON2.Tmp.Vector3[0];
var scale = BABYLON2.Tmp.Vector3[1];
var diffMatrix = BABYLON2.Tmp.Matrix[0];
var invParentMatrix = BABYLON2.Tmp.Matrix[1];
this.computeWorldMatrix(true);
node.computeWorldMatrix(true);
node.getWorldMatrix().invertToRef(invParentMatrix);
this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
diffMatrix.decompose(scale, rotation, position);
if (this.rotationQuaternion) {
this.rotationQuaternion.copyFrom(rotation);
} else {
rotation.toEulerAnglesToRef(this.rotation);
}
this.position.x = position.x;
this.position.y = position.y;
this.position.z = position.z;
this.scaling.x = scale.x;
this.scaling.y = scale.y;
this.scaling.z = scale.z;
}
this.parent = node;
return this;
};
Object.defineProperty(TransformNode2.prototype, "nonUniformScaling", {
/**
* True if the scaling property of this object is non uniform eg. (1,2,1)
*/
get: function() {
return this._nonUniformScaling;
},
enumerable: true,
configurable: true
});
TransformNode2.prototype._updateNonUniformScalingState = function(value) {
if (this._nonUniformScaling === value) {
return false;
}
this._nonUniformScaling = value;
return true;
};
TransformNode2.prototype.attachToBone = function(bone, affectedTransformNode) {
this._transformToBoneReferal = affectedTransformNode;
this.parent = bone;
if (bone.getWorldMatrix().determinant() < 0) {
this.scalingDeterminant *= -1;
}
return this;
};
TransformNode2.prototype.detachFromBone = function() {
if (!this.parent) {
return this;
}
if (this.parent.getWorldMatrix().determinant() < 0) {
this.scalingDeterminant *= -1;
}
this._transformToBoneReferal = null;
this.parent = null;
return this;
};
TransformNode2.prototype.rotate = function(axis, amount, space) {
axis.normalize();
if (!this.rotationQuaternion) {
this.rotationQuaternion = BABYLON2.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
this.rotation = BABYLON2.Vector3.Zero();
}
var rotationQuaternion;
if (!space || space === BABYLON2.Space.LOCAL) {
rotationQuaternion = BABYLON2.Quaternion.RotationAxisToRef(axis, amount, TransformNode2._rotationAxisCache);
this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
} else {
if (this.parent) {
var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
invertParentWorldMatrix.invert();
axis = BABYLON2.Vector3.TransformNormal(axis, invertParentWorldMatrix);
}
rotationQuaternion = BABYLON2.Quaternion.RotationAxisToRef(axis, amount, TransformNode2._rotationAxisCache);
rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
}
return this;
};
TransformNode2.prototype.rotateAround = function(point, axis, amount) {
axis.normalize();
if (!this.rotationQuaternion) {
this.rotationQuaternion = BABYLON2.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
this.rotation.copyFromFloats(0, 0, 0);
}
point.subtractToRef(this.position, BABYLON2.Tmp.Vector3[0]);
BABYLON2.Matrix.TranslationToRef(BABYLON2.Tmp.Vector3[0].x, BABYLON2.Tmp.Vector3[0].y, BABYLON2.Tmp.Vector3[0].z, BABYLON2.Tmp.Matrix[0]);
BABYLON2.Tmp.Matrix[0].invertToRef(BABYLON2.Tmp.Matrix[2]);
BABYLON2.Matrix.RotationAxisToRef(axis, amount, BABYLON2.Tmp.Matrix[1]);
BABYLON2.Tmp.Matrix[2].multiplyToRef(BABYLON2.Tmp.Matrix[1], BABYLON2.Tmp.Matrix[2]);
BABYLON2.Tmp.Matrix[2].multiplyToRef(BABYLON2.Tmp.Matrix[0], BABYLON2.Tmp.Matrix[2]);
BABYLON2.Tmp.Matrix[2].decompose(BABYLON2.Tmp.Vector3[0], BABYLON2.Tmp.Quaternion[0], BABYLON2.Tmp.Vector3[1]);
this.position.addInPlace(BABYLON2.Tmp.Vector3[1]);
BABYLON2.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
return this;
};
TransformNode2.prototype.translate = function(axis, distance, space) {
var displacementVector = axis.scale(distance);
if (!space || space === BABYLON2.Space.LOCAL) {
var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
this.setPositionWithLocalVector(tempV3);
} else {
this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
}
return this;
};
TransformNode2.prototype.addRotation = function(x, y, z) {
var rotationQuaternion;
if (this.rotationQuaternion) {
rotationQuaternion = this.rotationQuaternion;
} else {
rotationQuaternion = BABYLON2.Tmp.Quaternion[1];
BABYLON2.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
}
var accumulation = BABYLON2.Tmp.Quaternion[0];
BABYLON2.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
rotationQuaternion.multiplyInPlace(accumulation);
if (!this.rotationQuaternion) {
rotationQuaternion.toEulerAnglesToRef(this.rotation);
}
return this;
};
TransformNode2.prototype.computeWorldMatrix = function(force) {
if (this._isWorldMatrixFrozen) {
return this._worldMatrix;
}
if (!force && this.isSynchronized()) {
this._currentRenderId = this.getScene().getRenderId();
return this._worldMatrix;
}
this._updateCache();
this._cache.position.copyFrom(this.position);
this._cache.scaling.copyFrom(this.scaling);
this._cache.pivotMatrixUpdated = false;
this._cache.billboardMode = this.billboardMode;
this._currentRenderId = this.getScene().getRenderId();
this._childRenderId = this.getScene().getRenderId();
this._isDirty = false;
BABYLON2.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON2.Tmp.Matrix[1]);
if (this.rotationQuaternion) {
var len = this.rotation.length();
if (len) {
this.rotationQuaternion.multiplyInPlace(BABYLON2.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
this.rotation.copyFromFloats(0, 0, 0);
}
}
if (this.rotationQuaternion) {
this.rotationQuaternion.toRotationMatrix(BABYLON2.Tmp.Matrix[0]);
this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
} else {
BABYLON2.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON2.Tmp.Matrix[0]);
this._cache.rotation.copyFrom(this.rotation);
}
var camera2 = this.getScene().activeCamera;
if (this.infiniteDistance && !this.parent && camera2) {
var cameraWorldMatrix = camera2.getWorldMatrix();
BABYLON2.Tmp.Vector3[0].set(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
BABYLON2.Matrix.TranslationToRef(this.position.x + BABYLON2.Tmp.Vector3[0].x, this.position.y + BABYLON2.Tmp.Vector3[0].y, this.position.z + BABYLON2.Tmp.Vector3[0].z, BABYLON2.Tmp.Matrix[2]);
} else {
BABYLON2.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON2.Tmp.Matrix[2]);
}
this._pivotMatrix.multiplyToRef(BABYLON2.Tmp.Matrix[1], BABYLON2.Tmp.Matrix[4]);
BABYLON2.Tmp.Matrix[4].multiplyToRef(BABYLON2.Tmp.Matrix[0], BABYLON2.Tmp.Matrix[5]);
if (this.billboardMode !== TransformNode2.BILLBOARDMODE_NONE && camera2) {
if ((this.billboardMode & TransformNode2.BILLBOARDMODE_ALL) !== TransformNode2.BILLBOARDMODE_ALL) {
var currentPosition = BABYLON2.Tmp.Vector3[3];
if (this.parent && this.parent.getWorldMatrix) {
if (this._transformToBoneReferal) {
this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON2.Tmp.Matrix[6]);
BABYLON2.Vector3.TransformCoordinatesToRef(this.position, BABYLON2.Tmp.Matrix[6], currentPosition);
} else {
BABYLON2.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
}
} else {
currentPosition.copyFrom(this.position);
}
currentPosition.subtractInPlace(camera2.globalPosition);
var finalEuler = BABYLON2.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
if ((this.billboardMode & TransformNode2.BILLBOARDMODE_X) === TransformNode2.BILLBOARDMODE_X) {
finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
}
if ((this.billboardMode & TransformNode2.BILLBOARDMODE_Y) === TransformNode2.BILLBOARDMODE_Y) {
finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
}
if ((this.billboardMode & TransformNode2.BILLBOARDMODE_Z) === TransformNode2.BILLBOARDMODE_Z) {
finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
}
BABYLON2.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON2.Tmp.Matrix[0]);
} else {
BABYLON2.Tmp.Matrix[1].copyFrom(camera2.getViewMatrix());
BABYLON2.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
BABYLON2.Tmp.Matrix[1].invertToRef(BABYLON2.Tmp.Matrix[0]);
}
BABYLON2.Tmp.Matrix[1].copyFrom(BABYLON2.Tmp.Matrix[5]);
BABYLON2.Tmp.Matrix[1].multiplyToRef(BABYLON2.Tmp.Matrix[0], BABYLON2.Tmp.Matrix[5]);
}
if (this._postMultiplyPivotMatrix) {
BABYLON2.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON2.Tmp.Matrix[5]);
}
BABYLON2.Tmp.Matrix[5].multiplyToRef(BABYLON2.Tmp.Matrix[2], this._localWorld);
if (this.parent && this.parent.getWorldMatrix) {
if (this.billboardMode !== TransformNode2.BILLBOARDMODE_NONE) {
if (this._transformToBoneReferal) {
this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON2.Tmp.Matrix[6]);
BABYLON2.Tmp.Matrix[5].copyFrom(BABYLON2.Tmp.Matrix[6]);
} else {
BABYLON2.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
}
this._localWorld.getTranslationToRef(BABYLON2.Tmp.Vector3[5]);
BABYLON2.Vector3.TransformCoordinatesToRef(BABYLON2.Tmp.Vector3[5], BABYLON2.Tmp.Matrix[5], BABYLON2.Tmp.Vector3[5]);
this._worldMatrix.copyFrom(this._localWorld);
this._worldMatrix.setTranslation(BABYLON2.Tmp.Vector3[5]);
} else {
if (this._transformToBoneReferal) {
this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON2.Tmp.Matrix[6]);
BABYLON2.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
} else {
this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
}
}
this._markSyncedWithParent();
} else {
this._worldMatrix.copyFrom(this._localWorld);
}
if (!this.ignoreNonUniformScaling) {
if (this.scaling.isNonUniform) {
this._updateNonUniformScalingState(true);
} else if (this.parent && this.parent._nonUniformScaling) {
this._updateNonUniformScalingState(this.parent._nonUniformScaling);
} else {
this._updateNonUniformScalingState(false);
}
} else {
this._updateNonUniformScalingState(false);
}
this._afterComputeWorldMatrix();
this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
if (!this._poseMatrix) {
this._poseMatrix = BABYLON2.Matrix.Invert(this._worldMatrix);
}
this._worldMatrixDeterminant = this._worldMatrix.determinant();
return this._worldMatrix;
};
TransformNode2.prototype._afterComputeWorldMatrix = function() {
};
TransformNode2.prototype.registerAfterWorldMatrixUpdate = function(func) {
this.onAfterWorldMatrixUpdateObservable.add(func);
return this;
};
TransformNode2.prototype.unregisterAfterWorldMatrixUpdate = function(func) {
this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
return this;
};
TransformNode2.prototype.clone = function(name, newParent, doNotCloneChildren) {
var _this = this;
var result = BABYLON2.SerializationHelper.Clone(function() {
return new TransformNode2(name, _this.getScene());
}, this);
result.name = name;
result.id = name;
if (newParent) {
result.parent = newParent;
}
if (!doNotCloneChildren) {
var directDescendants = this.getDescendants(true);
for (var index = 0; index < directDescendants.length; index++) {
var child = directDescendants[index];
if (child.clone) {
child.clone(name + "." + child.name, result);
}
}
}
return result;
};
TransformNode2.prototype.serialize = function(currentSerializationObject) {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this, currentSerializationObject);
serializationObject.type = this.getClassName();
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
if (BABYLON2.Tags && BABYLON2.Tags.HasTags(this)) {
serializationObject.tags = BABYLON2.Tags.GetTags(this);
}
serializationObject.localMatrix = this.getPivotMatrix().asArray();
serializationObject.isEnabled = this.isEnabled();
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
return serializationObject;
};
TransformNode2.Parse = function(parsedTransformNode, scene, rootUrl) {
var transformNode = BABYLON2.SerializationHelper.Parse(function() {
return new TransformNode2(parsedTransformNode.name, scene);
}, parsedTransformNode, scene, rootUrl);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
}
if (parsedTransformNode.localMatrix) {
transformNode.setPreTransformMatrix(BABYLON2.Matrix.FromArray(parsedTransformNode.localMatrix));
} else if (parsedTransformNode.pivotMatrix) {
transformNode.setPivotMatrix(BABYLON2.Matrix.FromArray(parsedTransformNode.pivotMatrix));
}
transformNode.setEnabled(parsedTransformNode.isEnabled);
if (parsedTransformNode.parentId) {
transformNode._waitingParentId = parsedTransformNode.parentId;
}
return transformNode;
};
TransformNode2.prototype.dispose = function(doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) {
disposeMaterialAndTextures = false;
}
this.getScene().stopAnimation(this);
this.getScene().removeTransformNode(this);
this.onAfterWorldMatrixUpdateObservable.clear();
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
TransformNode2.BILLBOARDMODE_NONE = 0;
TransformNode2.BILLBOARDMODE_X = 1;
TransformNode2.BILLBOARDMODE_Y = 2;
TransformNode2.BILLBOARDMODE_Z = 4;
TransformNode2.BILLBOARDMODE_ALL = 7;
TransformNode2._lookAtVectorCache = new BABYLON2.Vector3(0, 0, 0);
TransformNode2._rotationAxisCache = new BABYLON2.Quaternion();
__decorate([
BABYLON2.serializeAsVector3("position")
], TransformNode2.prototype, "_position", void 0);
__decorate([
BABYLON2.serializeAsVector3("rotation")
], TransformNode2.prototype, "_rotation", void 0);
__decorate([
BABYLON2.serializeAsQuaternion("rotationQuaternion")
], TransformNode2.prototype, "_rotationQuaternion", void 0);
__decorate([
BABYLON2.serializeAsVector3("scaling")
], TransformNode2.prototype, "_scaling", void 0);
__decorate([
BABYLON2.serialize()
], TransformNode2.prototype, "billboardMode", void 0);
__decorate([
BABYLON2.serialize()
], TransformNode2.prototype, "scalingDeterminant", void 0);
__decorate([
BABYLON2.serialize()
], TransformNode2.prototype, "infiniteDistance", void 0);
__decorate([
BABYLON2.serialize()
], TransformNode2.prototype, "ignoreNonUniformScaling", void 0);
return TransformNode2;
}(BABYLON2.Node)
);
BABYLON2.TransformNode = TransformNode;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _FacetDataStorage = (
/** @class */
function() {
function _FacetDataStorage2() {
this.facetNb = 0;
this.partitioningSubdivisions = 10;
this.partitioningBBoxRatio = 1.01;
this.facetDataEnabled = false;
this.facetParameters = {};
this.bbSize = BABYLON2.Vector3.Zero();
this.subDiv = {
max: 1,
X: 1,
Y: 1,
Z: 1
};
this.facetDepthSort = false;
this.facetDepthSortEnabled = false;
}
return _FacetDataStorage2;
}()
);
var AbstractMesh = (
/** @class */
function(_super) {
__extends(AbstractMesh2, _super);
function AbstractMesh2(name, scene) {
if (scene === void 0) {
scene = null;
}
var _this = _super.call(this, name, scene, false) || this;
_this._facetData = new _FacetDataStorage();
_this.cullingStrategy = AbstractMesh2.CULLINGSTRATEGY_STANDARD;
_this.onCollideObservable = new BABYLON2.Observable();
_this.onCollisionPositionChangeObservable = new BABYLON2.Observable();
_this.onMaterialChangedObservable = new BABYLON2.Observable();
_this.definedFacingForward = true;
_this._visibility = 1;
_this.alphaIndex = Number.MAX_VALUE;
_this.isVisible = true;
_this.isPickable = true;
_this.showSubMeshesBoundingBox = false;
_this.isBlocker = false;
_this.enablePointerMoveEvents = false;
_this.renderingGroupId = 0;
_this._receiveShadows = false;
_this.outlineColor = BABYLON2.Color3.Red();
_this.outlineWidth = 0.02;
_this.overlayColor = BABYLON2.Color3.Red();
_this.overlayAlpha = 0.5;
_this._hasVertexAlpha = false;
_this._useVertexColors = true;
_this._computeBonesUsingShaders = true;
_this._numBoneInfluencers = 4;
_this._applyFog = true;
_this.useOctreeForRenderingSelection = true;
_this.useOctreeForPicking = true;
_this.useOctreeForCollisions = true;
_this._layerMask = 268435455;
_this.alwaysSelectAsActiveMesh = false;
_this.actionManager = null;
_this._checkCollisions = false;
_this._collisionMask = -1;
_this._collisionGroup = -1;
_this.ellipsoid = new BABYLON2.Vector3(0.5, 1, 0.5);
_this.ellipsoidOffset = new BABYLON2.Vector3(0, 0, 0);
_this._oldPositionForCollisions = new BABYLON2.Vector3(0, 0, 0);
_this._diffPositionForCollisions = new BABYLON2.Vector3(0, 0, 0);
_this.edgesWidth = 1;
_this.edgesColor = new BABYLON2.Color4(1, 0, 0, 1);
_this._renderId = 0;
_this._intersectionsInProgress = new Array();
_this._unIndexed = false;
_this._lightSources = new Array();
_this.onRebuildObservable = new BABYLON2.Observable();
_this._onCollisionPositionChange = function(collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) {
collidedMesh = null;
}
if (_this.getScene().workerCollisions) {
newPosition.multiplyInPlace(_this._collider._radius);
}
newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
if (_this._diffPositionForCollisions.length() > BABYLON2.Engine.CollisionsEpsilon) {
_this.position.addInPlace(_this._diffPositionForCollisions);
}
if (collidedMesh) {
_this.onCollideObservable.notifyObservers(collidedMesh);
}
_this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
};
_this.getScene().addMesh(_this);
_this._resyncLightSources();
return _this;
}
Object.defineProperty(AbstractMesh2, "BILLBOARDMODE_NONE", {
/**
* No billboard
*/
get: function() {
return BABYLON2.TransformNode.BILLBOARDMODE_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2, "BILLBOARDMODE_X", {
/** Billboard on X axis */
get: function() {
return BABYLON2.TransformNode.BILLBOARDMODE_X;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2, "BILLBOARDMODE_Y", {
/** Billboard on Y axis */
get: function() {
return BABYLON2.TransformNode.BILLBOARDMODE_Y;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2, "BILLBOARDMODE_Z", {
/** Billboard on Z axis */
get: function() {
return BABYLON2.TransformNode.BILLBOARDMODE_Z;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2, "BILLBOARDMODE_ALL", {
/** Billboard on all axes */
get: function() {
return BABYLON2.TransformNode.BILLBOARDMODE_ALL;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "facetNb", {
/**
* Gets the number of facets in the mesh
* @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
*/
get: function() {
return this._facetData.facetNb;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "partitioningSubdivisions", {
/**
* Gets or set the number (integer) of subdivisions per axis in the partioning space
* @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
*/
get: function() {
return this._facetData.partitioningSubdivisions;
},
set: function(nb) {
this._facetData.partitioningSubdivisions = nb;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "partitioningBBoxRatio", {
/**
* The ratio (float) to apply to the bouding box size to set to the partioning space.
* Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
* @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
*/
get: function() {
return this._facetData.partitioningBBoxRatio;
},
set: function(ratio) {
this._facetData.partitioningBBoxRatio = ratio;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "mustDepthSortFacets", {
/**
* Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
* Works only for updatable meshes.
* Doesn't work with multi-materials
* @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
*/
get: function() {
return this._facetData.facetDepthSort;
},
set: function(sort) {
this._facetData.facetDepthSort = sort;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "facetDepthSortFrom", {
/**
* The location (Vector3) where the facet depth sort must be computed from.
* By default, the active camera position.
* Used only when facet depth sort is enabled
* @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
*/
get: function() {
return this._facetData.facetDepthSortFrom;
},
set: function(location2) {
this._facetData.facetDepthSortFrom = location2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "isFacetDataEnabled", {
/**
* gets a boolean indicating if facetData is enabled
* @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
*/
get: function() {
return this._facetData.facetDataEnabled;
},
enumerable: true,
configurable: true
});
AbstractMesh2.prototype._updateNonUniformScalingState = function(value) {
if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
return false;
}
this._markSubMeshesAsMiscDirty();
return true;
};
Object.defineProperty(AbstractMesh2.prototype, "onCollide", {
/** Set a function to call when this mesh collides with another one */
set: function(callback) {
if (this._onCollideObserver) {
this.onCollideObservable.remove(this._onCollideObserver);
}
this._onCollideObserver = this.onCollideObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "onCollisionPositionChange", {
/** Set a function to call when the collision's position changes */
set: function(callback) {
if (this._onCollisionPositionChangeObserver) {
this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
}
this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "visibility", {
/**
* Gets or sets mesh visibility between 0 and 1 (default is 1)
*/
get: function() {
return this._visibility;
},
/**
* Gets or sets mesh visibility between 0 and 1 (default is 1)
*/
set: function(value) {
if (this._visibility === value) {
return;
}
this._visibility = value;
this._markSubMeshesAsMiscDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "material", {
/** Gets or sets current material */
get: function() {
return this._material;
},
set: function(value) {
if (this._material === value) {
return;
}
this._material = value;
if (this.onMaterialChangedObservable.hasObservers) {
this.onMaterialChangedObservable.notifyObservers(this);
}
if (!this.subMeshes) {
return;
}
this._unBindEffect();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "receiveShadows", {
/**
* Gets or sets a boolean indicating that this mesh can receive realtime shadows
* @see http://doc.babylonjs.com/babylon101/shadows
*/
get: function() {
return this._receiveShadows;
},
set: function(value) {
if (this._receiveShadows === value) {
return;
}
this._receiveShadows = value;
this._markSubMeshesAsLightDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "hasVertexAlpha", {
/** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
get: function() {
return this._hasVertexAlpha;
},
set: function(value) {
if (this._hasVertexAlpha === value) {
return;
}
this._hasVertexAlpha = value;
this._markSubMeshesAsAttributesDirty();
this._markSubMeshesAsMiscDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "useVertexColors", {
/** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
get: function() {
return this._useVertexColors;
},
set: function(value) {
if (this._useVertexColors === value) {
return;
}
this._useVertexColors = value;
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "computeBonesUsingShaders", {
/**
* Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
*/
get: function() {
return this._computeBonesUsingShaders;
},
set: function(value) {
if (this._computeBonesUsingShaders === value) {
return;
}
this._computeBonesUsingShaders = value;
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "numBoneInfluencers", {
/** Gets or sets the number of allowed bone influences per vertex (4 by default) */
get: function() {
return this._numBoneInfluencers;
},
set: function(value) {
if (this._numBoneInfluencers === value) {
return;
}
this._numBoneInfluencers = value;
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "applyFog", {
/** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
get: function() {
return this._applyFog;
},
set: function(value) {
if (this._applyFog === value) {
return;
}
this._applyFog = value;
this._markSubMeshesAsMiscDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "layerMask", {
/**
* Gets or sets the current layer mask (default is 0x0FFFFFFF)
* @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
*/
get: function() {
return this._layerMask;
},
set: function(value) {
if (value === this._layerMask) {
return;
}
this._layerMask = value;
this._resyncLightSources();
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "collisionMask", {
/**
* Gets or sets a collision mask used to mask collisions (default is -1).
* A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
*/
get: function() {
return this._collisionMask;
},
set: function(mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "collisionGroup", {
/**
* Gets or sets the current collision group mask (-1 by default).
* A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
*/
get: function() {
return this._collisionGroup;
},
set: function(mask) {
this._collisionGroup = !isNaN(mask) ? mask : -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "_positions", {
/** @hidden */
get: function() {
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "skeleton", {
get: function() {
return this._skeleton;
},
/**
* Gets or sets a skeleton to apply skining transformations
* @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
*/
set: function(value) {
if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
this._skeleton._unregisterMeshWithPoseMatrix(this);
}
if (value && value.needInitialSkinMatrix) {
value._registerMeshWithPoseMatrix(this);
}
this._skeleton = value;
if (!this._skeleton) {
this._bonesTransformMatrices = null;
}
this._markSubMeshesAsAttributesDirty();
},
enumerable: true,
configurable: true
});
AbstractMesh2.prototype.getClassName = function() {
return "AbstractMesh";
};
AbstractMesh2.prototype.toString = function(fullDetails) {
var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON2.InstancedMesh ? "YES" : "NO");
ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
if (this._skeleton) {
ret += ", skeleton: " + this._skeleton.name;
}
if (fullDetails) {
ret += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode];
ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
}
return ret;
};
AbstractMesh2.prototype._rebuild = function() {
this.onRebuildObservable.notifyObservers(this);
if (this._occlusionQuery) {
this._occlusionQuery = null;
}
if (!this.subMeshes) {
return;
}
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
subMesh._rebuild();
}
};
AbstractMesh2.prototype._resyncLightSources = function() {
this._lightSources.length = 0;
for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
var light = _a[_i];
if (!light.isEnabled()) {
continue;
}
if (light.canAffectMesh(this)) {
this._lightSources.push(light);
}
}
this._markSubMeshesAsLightDirty();
};
AbstractMesh2.prototype._resyncLighSource = function(light) {
var isIn = light.isEnabled() && light.canAffectMesh(this);
var index = this._lightSources.indexOf(light);
if (index === -1) {
if (!isIn) {
return;
}
this._lightSources.push(light);
} else {
if (isIn) {
return;
}
this._lightSources.splice(index, 1);
}
this._markSubMeshesAsLightDirty();
};
AbstractMesh2.prototype._unBindEffect = function() {
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
subMesh.setEffect(null);
}
};
AbstractMesh2.prototype._removeLightSource = function(light) {
var index = this._lightSources.indexOf(light);
if (index === -1) {
return;
}
this._lightSources.splice(index, 1);
this._markSubMeshesAsLightDirty();
};
AbstractMesh2.prototype._markSubMeshesAsDirty = function(func) {
if (!this.subMeshes) {
return;
}
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
if (subMesh._materialDefines) {
func(subMesh._materialDefines);
}
}
};
AbstractMesh2.prototype._markSubMeshesAsLightDirty = function() {
this._markSubMeshesAsDirty(function(defines) {
return defines.markAsLightDirty();
});
};
AbstractMesh2.prototype._markSubMeshesAsAttributesDirty = function() {
this._markSubMeshesAsDirty(function(defines) {
return defines.markAsAttributesDirty();
});
};
AbstractMesh2.prototype._markSubMeshesAsMiscDirty = function() {
if (!this.subMeshes) {
return;
}
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
var material = subMesh.getMaterial();
if (material) {
material.markAsDirty(BABYLON2.Material.MiscDirtyFlag);
}
}
};
Object.defineProperty(AbstractMesh2.prototype, "scaling", {
/**
* Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
*/
get: function() {
return this._scaling;
},
set: function(newScaling) {
this._scaling = newScaling;
if (this.physicsImpostor) {
this.physicsImpostor.forceUpdate();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "isBlocked", {
// Methods
/**
* Returns true if the mesh is blocked. Implemented by child classes
*/
get: function() {
return false;
},
enumerable: true,
configurable: true
});
AbstractMesh2.prototype.getLOD = function(camera2) {
return this;
};
AbstractMesh2.prototype.getTotalVertices = function() {
return 0;
};
AbstractMesh2.prototype.getIndices = function() {
return null;
};
AbstractMesh2.prototype.getVerticesData = function(kind) {
return null;
};
AbstractMesh2.prototype.setVerticesData = function(kind, data2, updatable, stride) {
return this;
};
AbstractMesh2.prototype.updateVerticesData = function(kind, data2, updateExtends, makeItUnique) {
return this;
};
AbstractMesh2.prototype.setIndices = function(indices, totalVertices) {
return this;
};
AbstractMesh2.prototype.isVerticesDataPresent = function(kind) {
return false;
};
AbstractMesh2.prototype.getBoundingInfo = function() {
if (this._masterMesh) {
return this._masterMesh.getBoundingInfo();
}
if (!this._boundingInfo) {
this._updateBoundingInfo();
}
return this._boundingInfo;
};
AbstractMesh2.prototype.normalizeToUnitCube = function(includeDescendants) {
if (includeDescendants === void 0) {
includeDescendants = true;
}
var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
if (maxDimension === 0) {
return this;
}
var scale = 1 / maxDimension;
this.scaling.scaleInPlace(scale);
return this;
};
AbstractMesh2.prototype.setBoundingInfo = function(boundingInfo) {
this._boundingInfo = boundingInfo;
return this;
};
Object.defineProperty(AbstractMesh2.prototype, "useBones", {
/** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
get: function() {
return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesWeightsKind);
},
enumerable: true,
configurable: true
});
AbstractMesh2.prototype._preActivate = function() {
};
AbstractMesh2.prototype._preActivateForIntermediateRendering = function(renderId) {
};
AbstractMesh2.prototype._activate = function(renderId) {
this._renderId = renderId;
};
AbstractMesh2.prototype.getWorldMatrix = function() {
if (this._masterMesh) {
return this._masterMesh.getWorldMatrix();
}
return _super.prototype.getWorldMatrix.call(this);
};
AbstractMesh2.prototype._getWorldMatrixDeterminant = function() {
if (this._masterMesh) {
return this._masterMesh._getWorldMatrixDeterminant();
}
return _super.prototype._getWorldMatrixDeterminant.call(this);
};
AbstractMesh2.prototype.movePOV = function(amountRight, amountUp, amountForward) {
this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
return this;
};
AbstractMesh2.prototype.calcMovePOV = function(amountRight, amountUp, amountForward) {
var rotMatrix = new BABYLON2.Matrix();
var rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : BABYLON2.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
rotQuaternion.toRotationMatrix(rotMatrix);
var translationDelta = BABYLON2.Vector3.Zero();
var defForwardMult = this.definedFacingForward ? -1 : 1;
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
return translationDelta;
};
AbstractMesh2.prototype.rotatePOV = function(flipBack, twirlClockwise, tiltRight) {
this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
return this;
};
AbstractMesh2.prototype.calcRotatePOV = function(flipBack, twirlClockwise, tiltRight) {
var defForwardMult = this.definedFacingForward ? 1 : -1;
return new BABYLON2.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
};
AbstractMesh2.prototype.getHierarchyBoundingVectors = function(includeDescendants, predicate) {
if (includeDescendants === void 0) {
includeDescendants = true;
}
if (predicate === void 0) {
predicate = null;
}
this.getScene().incrementRenderId();
this.computeWorldMatrix(true);
var min;
var max;
var boundingInfo = this.getBoundingInfo();
if (!this.subMeshes) {
min = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
max = new BABYLON2.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
} else {
min = boundingInfo.boundingBox.minimumWorld;
max = boundingInfo.boundingBox.maximumWorld;
}
if (includeDescendants) {
var descendants = this.getDescendants(false);
for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
var descendant = descendants_1[_i];
var childMesh = descendant;
childMesh.computeWorldMatrix(true);
if (predicate && !predicate(childMesh)) {
continue;
}
if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
continue;
}
var childBoundingInfo = childMesh.getBoundingInfo();
var boundingBox = childBoundingInfo.boundingBox;
var minBox = boundingBox.minimumWorld;
var maxBox = boundingBox.maximumWorld;
BABYLON2.Tools.CheckExtends(minBox, min, max);
BABYLON2.Tools.CheckExtends(maxBox, min, max);
}
}
return {
min,
max
};
};
AbstractMesh2.prototype._updateBoundingInfo = function() {
this._boundingInfo = this._boundingInfo || new BABYLON2.BoundingInfo(this.absolutePosition, this.absolutePosition);
this._boundingInfo.update(this.worldMatrixFromCache);
this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
return this;
};
AbstractMesh2.prototype._updateSubMeshesBoundingInfo = function(matrix) {
if (!this.subMeshes) {
return this;
}
var count = this.subMeshes.length;
for (var subIndex = 0; subIndex < count; subIndex++) {
var subMesh = this.subMeshes[subIndex];
if (count > 1 || !subMesh.IsGlobal) {
subMesh.updateBoundingInfo(matrix);
}
}
return this;
};
AbstractMesh2.prototype._afterComputeWorldMatrix = function() {
this._updateBoundingInfo();
};
AbstractMesh2.prototype.isInFrustum = function(frustumPlanes) {
return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
};
AbstractMesh2.prototype.isCompletelyInFrustum = function(frustumPlanes) {
return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
};
AbstractMesh2.prototype.intersectsMesh = function(mesh2, precise, includeDescendants) {
if (precise === void 0) {
precise = false;
}
if (!this._boundingInfo || !mesh2._boundingInfo) {
return false;
}
if (this._boundingInfo.intersects(mesh2._boundingInfo, precise)) {
return this;
}
if (includeDescendants) {
for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
var child = _a[_i];
if (child.intersectsMesh(mesh2, precise, true)) {
return child;
}
}
}
return false;
};
AbstractMesh2.prototype.intersectsPoint = function(point, useLocal) {
if (!this._boundingInfo) {
return false;
}
return this._boundingInfo.intersectsPoint(point, useLocal);
};
AbstractMesh2.prototype.getPositionInCameraSpace = function(camera2) {
if (camera2 === void 0) {
camera2 = null;
}
if (!camera2) {
camera2 = this.getScene().activeCamera;
}
return BABYLON2.Vector3.TransformCoordinates(this.absolutePosition, camera2.getViewMatrix());
};
AbstractMesh2.prototype.getDistanceToCamera = function(camera2) {
if (camera2 === void 0) {
camera2 = null;
}
if (!camera2) {
camera2 = this.getScene().activeCamera;
}
return this.absolutePosition.subtract(camera2.position).length();
};
Object.defineProperty(AbstractMesh2.prototype, "checkCollisions", {
// Collisions
/**
* Gets or sets a boolean indicating that this mesh can be used in the collision engine
* @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
*/
get: function() {
return this._checkCollisions;
},
set: function(collisionEnabled) {
this._checkCollisions = collisionEnabled;
if (this.getScene().workerCollisions) {
this.getScene().collisionCoordinator.onMeshUpdated(this);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractMesh2.prototype, "collider", {
/**
* Gets Collider object used to compute collisions (not physics)
* @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
*/
get: function() {
return this._collider;
},
enumerable: true,
configurable: true
});
AbstractMesh2.prototype.moveWithCollisions = function(displacement) {
var globalPosition = this.getAbsolutePosition();
globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
if (!this._collider) {
this._collider = new BABYLON2.Collider();
}
this._collider._radius = this.ellipsoid;
this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
return this;
};
AbstractMesh2.prototype._collideForSubMesh = function(subMesh, transformMatrix, collider) {
this._generatePointsArray();
if (!this._positions) {
return this;
}
if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
subMesh._lastColliderTransformMatrix = transformMatrix.clone();
subMesh._lastColliderWorldVertices = [];
subMesh._trianglePlanes = [];
var start = subMesh.verticesStart;
var end = subMesh.verticesStart + subMesh.verticesCount;
for (var i2 = start; i2 < end; i2++) {
subMesh._lastColliderWorldVertices.push(BABYLON2.Vector3.TransformCoordinates(this._positions[i2], transformMatrix));
}
}
collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
if (collider.collisionFound) {
collider.collidedMesh = this;
}
return this;
};
AbstractMesh2.prototype._processCollisionsForSubMeshes = function(collider, transformMatrix) {
var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
var len = subMeshes.length;
for (var index = 0; index < len; index++) {
var subMesh = subMeshes.data[index];
if (len > 1 && !subMesh._checkCollision(collider)) {
continue;
}
this._collideForSubMesh(subMesh, transformMatrix, collider);
}
return this;
};
AbstractMesh2.prototype._checkCollision = function(collider) {
if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
return this;
}
var collisionsScalingMatrix = BABYLON2.Tmp.Matrix[0];
var collisionsTransformMatrix = BABYLON2.Tmp.Matrix[1];
BABYLON2.Matrix.ScalingToRef(1 / collider._radius.x, 1 / collider._radius.y, 1 / collider._radius.z, collisionsScalingMatrix);
this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
return this;
};
AbstractMesh2.prototype._generatePointsArray = function() {
return false;
};
AbstractMesh2.prototype.intersects = function(ray, fastCheck) {
var pickingInfo = new BABYLON2.PickingInfo();
if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
return pickingInfo;
}
if (!this._generatePointsArray()) {
return pickingInfo;
}
var intersectInfo = null;
var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
var len = subMeshes.length;
for (var index = 0; index < len; index++) {
var subMesh = subMeshes.data[index];
if (len > 1 && !subMesh.canIntersects(ray)) {
continue;
}
var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
if (currentIntersectInfo) {
if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
intersectInfo = currentIntersectInfo;
intersectInfo.subMeshId = index;
if (fastCheck) {
break;
}
}
}
}
if (intersectInfo) {
var world = this.getWorldMatrix();
var worldOrigin = BABYLON2.Vector3.TransformCoordinates(ray.origin, world);
var direction = ray.direction.clone();
direction = direction.scale(intersectInfo.distance);
var worldDirection = BABYLON2.Vector3.TransformNormal(direction, world);
var pickedPoint = worldOrigin.add(worldDirection);
pickingInfo.hit = true;
pickingInfo.distance = BABYLON2.Vector3.Distance(worldOrigin, pickedPoint);
pickingInfo.pickedPoint = pickedPoint;
pickingInfo.pickedMesh = this;
pickingInfo.bu = intersectInfo.bu || 0;
pickingInfo.bv = intersectInfo.bv || 0;
pickingInfo.faceId = intersectInfo.faceId;
pickingInfo.subMeshId = intersectInfo.subMeshId;
return pickingInfo;
}
return pickingInfo;
};
AbstractMesh2.prototype.clone = function(name, newParent, doNotCloneChildren) {
return null;
};
AbstractMesh2.prototype.releaseSubMeshes = function() {
if (this.subMeshes) {
while (this.subMeshes.length) {
this.subMeshes[0].dispose();
}
} else {
this.subMeshes = new Array();
}
return this;
};
AbstractMesh2.prototype.dispose = function(doNotRecurse, disposeMaterialAndTextures) {
var _this = this;
if (disposeMaterialAndTextures === void 0) {
disposeMaterialAndTextures = false;
}
var index;
this.getScene().freeActiveMeshes();
this.getScene().freeRenderingGroups();
if (this.actionManager !== void 0 && this.actionManager !== null) {
this.actionManager.dispose();
this.actionManager = null;
}
this._skeleton = null;
for (index = 0; index < this._intersectionsInProgress.length; index++) {
var other = this._intersectionsInProgress[index];
var pos = other._intersectionsInProgress.indexOf(this);
other._intersectionsInProgress.splice(pos, 1);
}
this._intersectionsInProgress = [];
var lights = this.getScene().lights;
lights.forEach(function(light) {
var meshIndex = light.includedOnlyMeshes.indexOf(_this);
if (meshIndex !== -1) {
light.includedOnlyMeshes.splice(meshIndex, 1);
}
meshIndex = light.excludedMeshes.indexOf(_this);
if (meshIndex !== -1) {
light.excludedMeshes.splice(meshIndex, 1);
}
var generator = light.getShadowGenerator();
if (generator) {
var shadowMap = generator.getShadowMap();
if (shadowMap && shadowMap.renderList) {
meshIndex = shadowMap.renderList.indexOf(_this);
if (meshIndex !== -1) {
shadowMap.renderList.splice(meshIndex, 1);
}
}
}
});
if (this.getClassName() !== "InstancedMesh") {
this.releaseSubMeshes();
}
var engine = this.getScene().getEngine();
if (this._occlusionQuery) {
this.isOcclusionQueryInProgress = false;
engine.deleteQuery(this._occlusionQuery);
this._occlusionQuery = null;
}
engine.wipeCaches();
this.getScene().removeMesh(this);
if (disposeMaterialAndTextures) {
if (this.material) {
this.material.dispose(false, true);
}
}
if (!doNotRecurse) {
for (index = 0; index < this.getScene().particleSystems.length; index++) {
if (this.getScene().particleSystems[index].emitter === this) {
this.getScene().particleSystems[index].dispose();
index--;
}
}
}
if (this._facetData.facetDataEnabled) {
this.disableFacetData();
}
this.onAfterWorldMatrixUpdateObservable.clear();
this.onCollideObservable.clear();
this.onCollisionPositionChangeObservable.clear();
this.onRebuildObservable.clear();
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
AbstractMesh2.prototype.addChild = function(mesh2) {
mesh2.setParent(this);
return this;
};
AbstractMesh2.prototype.removeChild = function(mesh2) {
mesh2.setParent(null);
return this;
};
AbstractMesh2.prototype._initFacetData = function() {
var data2 = this._facetData;
if (!data2.facetNormals) {
data2.facetNormals = new Array();
}
if (!data2.facetPositions) {
data2.facetPositions = new Array();
}
if (!data2.facetPartitioning) {
data2.facetPartitioning = new Array();
}
data2.facetNb = this.getIndices().length / 3 | 0;
data2.partitioningSubdivisions = data2.partitioningSubdivisions ? data2.partitioningSubdivisions : 10;
data2.partitioningBBoxRatio = data2.partitioningBBoxRatio ? data2.partitioningBBoxRatio : 1.01;
for (var f = 0; f < data2.facetNb; f++) {
data2.facetNormals[f] = BABYLON2.Vector3.Zero();
data2.facetPositions[f] = BABYLON2.Vector3.Zero();
}
data2.facetDataEnabled = true;
return this;
};
AbstractMesh2.prototype.updateFacetData = function() {
var data2 = this._facetData;
if (!data2.facetDataEnabled) {
this._initFacetData();
}
var positions = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var indices = this.getIndices();
var normals = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var bInfo = this.getBoundingInfo();
if (data2.facetDepthSort && !data2.facetDepthSortEnabled) {
data2.facetDepthSortEnabled = true;
if (indices instanceof Uint16Array) {
data2.depthSortedIndices = new Uint16Array(indices);
} else if (indices instanceof Uint32Array) {
data2.depthSortedIndices = new Uint32Array(indices);
} else {
var needs32bits = false;
for (var i2 = 0; i2 < indices.length; i2++) {
if (indices[i2] > 65535) {
needs32bits = true;
break;
}
}
if (needs32bits) {
data2.depthSortedIndices = new Uint32Array(indices);
} else {
data2.depthSortedIndices = new Uint16Array(indices);
}
}
data2.facetDepthSortFunction = function(f1, f2) {
return f2.sqDistance - f1.sqDistance;
};
if (!data2.facetDepthSortFrom) {
var camera2 = this.getScene().activeCamera;
data2.facetDepthSortFrom = camera2 ? camera2.position : BABYLON2.Vector3.Zero();
}
data2.depthSortedFacets = [];
for (var f = 0; f < data2.facetNb; f++) {
var depthSortedFacet = { ind: f * 3, sqDistance: 0 };
data2.depthSortedFacets.push(depthSortedFacet);
}
data2.invertedMatrix = BABYLON2.Matrix.Identity();
data2.facetDepthSortOrigin = BABYLON2.Vector3.Zero();
}
data2.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > BABYLON2.Epsilon ? bInfo.maximum.x - bInfo.minimum.x : BABYLON2.Epsilon;
data2.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > BABYLON2.Epsilon ? bInfo.maximum.y - bInfo.minimum.y : BABYLON2.Epsilon;
data2.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > BABYLON2.Epsilon ? bInfo.maximum.z - bInfo.minimum.z : BABYLON2.Epsilon;
var bbSizeMax = data2.bbSize.x > data2.bbSize.y ? data2.bbSize.x : data2.bbSize.y;
bbSizeMax = bbSizeMax > data2.bbSize.z ? bbSizeMax : data2.bbSize.z;
data2.subDiv.max = data2.partitioningSubdivisions;
data2.subDiv.X = Math.floor(data2.subDiv.max * data2.bbSize.x / bbSizeMax);
data2.subDiv.Y = Math.floor(data2.subDiv.max * data2.bbSize.y / bbSizeMax);
data2.subDiv.Z = Math.floor(data2.subDiv.max * data2.bbSize.z / bbSizeMax);
data2.subDiv.X = data2.subDiv.X < 1 ? 1 : data2.subDiv.X;
data2.subDiv.Y = data2.subDiv.Y < 1 ? 1 : data2.subDiv.Y;
data2.subDiv.Z = data2.subDiv.Z < 1 ? 1 : data2.subDiv.Z;
data2.facetParameters.facetNormals = this.getFacetLocalNormals();
data2.facetParameters.facetPositions = this.getFacetLocalPositions();
data2.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
data2.facetParameters.bInfo = bInfo;
data2.facetParameters.bbSize = data2.bbSize;
data2.facetParameters.subDiv = data2.subDiv;
data2.facetParameters.ratio = this.partitioningBBoxRatio;
data2.facetParameters.depthSort = data2.facetDepthSort;
if (data2.facetDepthSort && data2.facetDepthSortEnabled) {
this.computeWorldMatrix(true);
this._worldMatrix.invertToRef(data2.invertedMatrix);
BABYLON2.Vector3.TransformCoordinatesToRef(data2.facetDepthSortFrom, data2.invertedMatrix, data2.facetDepthSortOrigin);
data2.facetParameters.distanceTo = data2.facetDepthSortOrigin;
}
data2.facetParameters.depthSortedFacets = data2.depthSortedFacets;
BABYLON2.VertexData.ComputeNormals(positions, indices, normals, data2.facetParameters);
if (data2.facetDepthSort && data2.facetDepthSortEnabled) {
data2.depthSortedFacets.sort(data2.facetDepthSortFunction);
var l = data2.depthSortedIndices.length / 3 | 0;
for (var f = 0; f < l; f++) {
var sind = data2.depthSortedFacets[f].ind;
data2.depthSortedIndices[f * 3] = indices[sind];
data2.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
data2.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
}
this.updateIndices(data2.depthSortedIndices);
}
return this;
};
AbstractMesh2.prototype.getFacetLocalNormals = function() {
if (!this._facetData.facetNormals) {
this.updateFacetData();
}
return this._facetData.facetNormals;
};
AbstractMesh2.prototype.getFacetLocalPositions = function() {
if (!this._facetData.facetPositions) {
this.updateFacetData();
}
return this._facetData.facetPositions;
};
AbstractMesh2.prototype.getFacetLocalPartitioning = function() {
if (!this._facetData.facetPartitioning) {
this.updateFacetData();
}
return this._facetData.facetPartitioning;
};
AbstractMesh2.prototype.getFacetPosition = function(i2) {
var pos = BABYLON2.Vector3.Zero();
this.getFacetPositionToRef(i2, pos);
return pos;
};
AbstractMesh2.prototype.getFacetPositionToRef = function(i2, ref) {
var localPos = this.getFacetLocalPositions()[i2];
var world = this.getWorldMatrix();
BABYLON2.Vector3.TransformCoordinatesToRef(localPos, world, ref);
return this;
};
AbstractMesh2.prototype.getFacetNormal = function(i2) {
var norm = BABYLON2.Vector3.Zero();
this.getFacetNormalToRef(i2, norm);
return norm;
};
AbstractMesh2.prototype.getFacetNormalToRef = function(i2, ref) {
var localNorm = this.getFacetLocalNormals()[i2];
BABYLON2.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
return this;
};
AbstractMesh2.prototype.getFacetsAtLocalCoordinates = function(x, y, z) {
var bInfo = this.getBoundingInfo();
var data2 = this._facetData;
var ox = Math.floor((x - bInfo.minimum.x * data2.partitioningBBoxRatio) * data2.subDiv.X * data2.partitioningBBoxRatio / data2.bbSize.x);
var oy = Math.floor((y - bInfo.minimum.y * data2.partitioningBBoxRatio) * data2.subDiv.Y * data2.partitioningBBoxRatio / data2.bbSize.y);
var oz = Math.floor((z - bInfo.minimum.z * data2.partitioningBBoxRatio) * data2.subDiv.Z * data2.partitioningBBoxRatio / data2.bbSize.z);
if (ox < 0 || ox > data2.subDiv.max || oy < 0 || oy > data2.subDiv.max || oz < 0 || oz > data2.subDiv.max) {
return null;
}
return data2.facetPartitioning[ox + data2.subDiv.max * oy + data2.subDiv.max * data2.subDiv.max * oz];
};
AbstractMesh2.prototype.getClosestFacetAtCoordinates = function(x, y, z, projected, checkFace, facing) {
if (checkFace === void 0) {
checkFace = false;
}
if (facing === void 0) {
facing = true;
}
var world = this.getWorldMatrix();
var invMat = BABYLON2.Tmp.Matrix[5];
world.invertToRef(invMat);
var invVect = BABYLON2.Tmp.Vector3[8];
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect);
var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
if (projected) {
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
}
return closest;
};
AbstractMesh2.prototype.getClosestFacetAtLocalCoordinates = function(x, y, z, projected, checkFace, facing) {
if (checkFace === void 0) {
checkFace = false;
}
if (facing === void 0) {
facing = true;
}
var closest = null;
var tmpx = 0;
var tmpy = 0;
var tmpz = 0;
var d = 0;
var t0 = 0;
var projx = 0;
var projy = 0;
var projz = 0;
var facetPositions = this.getFacetLocalPositions();
var facetNormals = this.getFacetLocalNormals();
var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
if (!facetsInBlock) {
return null;
}
var shortest = Number.MAX_VALUE;
var tmpDistance = shortest;
var fib;
var norm;
var p0;
for (var idx = 0; idx < facetsInBlock.length; idx++) {
fib = facetsInBlock[idx];
norm = facetNormals[fib];
p0 = facetPositions[fib];
d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
if (!checkFace || checkFace && facing && d >= 0 || checkFace && !facing && d <= 0) {
d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
projx = x + norm.x * t0;
projy = y + norm.y * t0;
projz = z + norm.z * t0;
tmpx = projx - x;
tmpy = projy - y;
tmpz = projz - z;
tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz;
if (tmpDistance < shortest) {
shortest = tmpDistance;
closest = fib;
if (projected) {
projected.x = projx;
projected.y = projy;
projected.z = projz;
}
}
}
}
return closest;
};
AbstractMesh2.prototype.getFacetDataParameters = function() {
return this._facetData.facetParameters;
};
AbstractMesh2.prototype.disableFacetData = function() {
if (this._facetData.facetDataEnabled) {
this._facetData.facetDataEnabled = false;
this._facetData.facetPositions = new Array();
this._facetData.facetNormals = new Array();
this._facetData.facetPartitioning = new Array();
this._facetData.facetParameters = null;
this._facetData.depthSortedIndices = new Uint32Array(0);
}
return this;
};
AbstractMesh2.prototype.updateIndices = function(indices) {
return this;
};
AbstractMesh2.prototype.createNormals = function(updatable) {
var positions = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var indices = this.getIndices();
var normals;
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
normals = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
} else {
normals = [];
}
BABYLON2.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
this.setVerticesData(BABYLON2.VertexBuffer.NormalKind, normals, updatable);
return this;
};
AbstractMesh2.prototype.alignWithNormal = function(normal, upDirection) {
if (!upDirection) {
upDirection = BABYLON2.Axis.Y;
}
var axisX = BABYLON2.Tmp.Vector3[0];
var axisZ = BABYLON2.Tmp.Vector3[1];
BABYLON2.Vector3.CrossToRef(upDirection, normal, axisZ);
BABYLON2.Vector3.CrossToRef(normal, axisZ, axisX);
if (this.rotationQuaternion) {
BABYLON2.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
} else {
BABYLON2.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
}
return this;
};
AbstractMesh2.prototype._checkOcclusionQuery = function() {
return false;
};
AbstractMesh2.OCCLUSION_TYPE_NONE = 0;
AbstractMesh2.OCCLUSION_TYPE_OPTIMISTIC = 1;
AbstractMesh2.OCCLUSION_TYPE_STRICT = 2;
AbstractMesh2.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
AbstractMesh2.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
AbstractMesh2.CULLINGSTRATEGY_STANDARD = 0;
AbstractMesh2.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
return AbstractMesh2;
}(BABYLON2.TransformNode)
);
BABYLON2.AbstractMesh = AbstractMesh;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Light = (
/** @class */
function(_super) {
__extends(Light2, _super);
function Light2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.diffuse = new BABYLON2.Color3(1, 1, 1);
_this.specular = new BABYLON2.Color3(1, 1, 1);
_this.falloffType = Light2.FALLOFF_DEFAULT;
_this.intensity = 1;
_this._range = Number.MAX_VALUE;
_this._inverseSquaredRange = 0;
_this._photometricScale = 1;
_this._intensityMode = Light2.INTENSITYMODE_AUTOMATIC;
_this._radius = 1e-5;
_this.renderPriority = 0;
_this._shadowEnabled = true;
_this._excludeWithLayerMask = 0;
_this._includeOnlyWithLayerMask = 0;
_this._lightmapMode = 0;
_this._excludedMeshesIds = new Array();
_this._includedOnlyMeshesIds = new Array();
_this.getScene().addLight(_this);
_this._uniformBuffer = new BABYLON2.UniformBuffer(_this.getScene().getEngine());
_this._buildUniformLayout();
_this.includedOnlyMeshes = new Array();
_this.excludedMeshes = new Array();
_this._resyncMeshes();
return _this;
}
Object.defineProperty(Light2.prototype, "range", {
/**
* Defines how far from the source the light is impacting in scene units.
* Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
*/
get: function() {
return this._range;
},
/**
* Defines how far from the source the light is impacting in scene units.
* Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
*/
set: function(value) {
this._range = value;
this._inverseSquaredRange = 1 / (this.range * this.range);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "intensityMode", {
/**
* Gets the photometric scale used to interpret the intensity.
* This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
*/
get: function() {
return this._intensityMode;
},
/**
* Sets the photometric scale used to interpret the intensity.
* This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
*/
set: function(value) {
this._intensityMode = value;
this._computePhotometricScale();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "radius", {
/**
* Gets the light radius used by PBR Materials to simulate soft area lights.
*/
get: function() {
return this._radius;
},
/**
* sets the light radius used by PBR Materials to simulate soft area lights.
*/
set: function(value) {
this._radius = value;
this._computePhotometricScale();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "shadowEnabled", {
/**
* Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
* the current shadow generator.
*/
get: function() {
return this._shadowEnabled;
},
/**
* Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
* the current shadow generator.
*/
set: function(value) {
if (this._shadowEnabled === value) {
return;
}
this._shadowEnabled = value;
this._markMeshesAsLightDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "includedOnlyMeshes", {
/**
* Gets the only meshes impacted by this light.
*/
get: function() {
return this._includedOnlyMeshes;
},
/**
* Sets the only meshes impacted by this light.
*/
set: function(value) {
this._includedOnlyMeshes = value;
this._hookArrayForIncludedOnly(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "excludedMeshes", {
/**
* Gets the meshes not impacted by this light.
*/
get: function() {
return this._excludedMeshes;
},
/**
* Sets the meshes not impacted by this light.
*/
set: function(value) {
this._excludedMeshes = value;
this._hookArrayForExcluded(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "excludeWithLayerMask", {
/**
* Gets the layer id use to find what meshes are not impacted by the light.
* Inactive if 0
*/
get: function() {
return this._excludeWithLayerMask;
},
/**
* Sets the layer id use to find what meshes are not impacted by the light.
* Inactive if 0
*/
set: function(value) {
this._excludeWithLayerMask = value;
this._resyncMeshes();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "includeOnlyWithLayerMask", {
/**
* Gets the layer id use to find what meshes are impacted by the light.
* Inactive if 0
*/
get: function() {
return this._includeOnlyWithLayerMask;
},
/**
* Sets the layer id use to find what meshes are impacted by the light.
* Inactive if 0
*/
set: function(value) {
this._includeOnlyWithLayerMask = value;
this._resyncMeshes();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Light2.prototype, "lightmapMode", {
/**
* Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
*/
get: function() {
return this._lightmapMode;
},
/**
* Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
*/
set: function(value) {
if (this._lightmapMode === value) {
return;
}
this._lightmapMode = value;
this._markMeshesAsLightDirty();
},
enumerable: true,
configurable: true
});
Light2.prototype.getClassName = function() {
return "Light";
};
Light2.prototype.toString = function(fullDetails) {
var ret = "Name: " + this.name;
ret += ", type: " + ["Point", "Directional", "Spot", "Hemispheric"][this.getTypeID()];
if (this.animations) {
for (var i2 = 0; i2 < this.animations.length; i2++) {
ret += ", animation[0]: " + this.animations[i2].toString(fullDetails);
}
}
if (fullDetails) {
}
return ret;
};
Light2.prototype._syncParentEnabledState = function() {
_super.prototype._syncParentEnabledState.call(this);
this._resyncMeshes();
};
Light2.prototype.setEnabled = function(value) {
_super.prototype.setEnabled.call(this, value);
this._resyncMeshes();
};
Light2.prototype.getShadowGenerator = function() {
return this._shadowGenerator;
};
Light2.prototype.getAbsolutePosition = function() {
return BABYLON2.Vector3.Zero();
};
Light2.prototype.canAffectMesh = function(mesh2) {
if (!mesh2) {
return true;
}
if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh2) === -1) {
return false;
}
if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh2) !== -1) {
return false;
}
if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh2.layerMask) === 0) {
return false;
}
if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh2.layerMask) {
return false;
}
return true;
};
Light2.CompareLightsPriority = function(a, b2) {
if (a.shadowEnabled !== b2.shadowEnabled) {
return (b2.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
}
return b2.renderPriority - a.renderPriority;
};
Light2.prototype.dispose = function(doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) {
disposeMaterialAndTextures = false;
}
if (this._shadowGenerator) {
this._shadowGenerator.dispose();
this._shadowGenerator = null;
}
this.getScene().stopAnimation(this);
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
mesh2._removeLightSource(this);
}
this._uniformBuffer.dispose();
this.getScene().removeLight(this);
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
Light2.prototype.getTypeID = function() {
return 0;
};
Light2.prototype.getScaledIntensity = function() {
return this._photometricScale * this.intensity;
};
Light2.prototype.clone = function(name) {
var constructor = Light2.GetConstructorFromName(this.getTypeID(), name, this.getScene());
if (!constructor) {
return null;
}
return BABYLON2.SerializationHelper.Clone(constructor, this);
};
Light2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.type = this.getTypeID();
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
if (this.excludedMeshes.length > 0) {
serializationObject.excludedMeshesIds = [];
this.excludedMeshes.forEach(function(mesh2) {
serializationObject.excludedMeshesIds.push(mesh2.id);
});
}
if (this.includedOnlyMeshes.length > 0) {
serializationObject.includedOnlyMeshesIds = [];
this.includedOnlyMeshes.forEach(function(mesh2) {
serializationObject.includedOnlyMeshesIds.push(mesh2.id);
});
}
BABYLON2.Animation.AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
return serializationObject;
};
Light2.GetConstructorFromName = function(type, name, scene) {
var constructorFunc = BABYLON2.Node.Construct("Light_Type_" + type, name, scene);
if (constructorFunc) {
return constructorFunc;
}
return null;
};
Light2.Parse = function(parsedLight, scene) {
var constructor = Light2.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
if (!constructor) {
return null;
}
var light = BABYLON2.SerializationHelper.Parse(constructor, parsedLight, scene);
if (parsedLight.excludedMeshesIds) {
light._excludedMeshesIds = parsedLight.excludedMeshesIds;
}
if (parsedLight.includedOnlyMeshesIds) {
light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
}
if (parsedLight.parentId) {
light._waitingParentId = parsedLight.parentId;
}
if (parsedLight.animations) {
for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
var parsedAnimation = parsedLight.animations[animationIndex];
light.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
BABYLON2.Node.ParseAnimationRanges(light, parsedLight, scene);
}
if (parsedLight.autoAnimate) {
scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1);
}
return light;
};
Light2.prototype._hookArrayForExcluded = function(array) {
var _this = this;
var oldPush = array.push;
array.push = function() {
var items = [];
for (var _i2 = 0; _i2 < arguments.length; _i2++) {
items[_i2] = arguments[_i2];
}
var result = oldPush.apply(array, items);
for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
var item2 = items_1[_a];
item2._resyncLighSource(_this);
}
return result;
};
var oldSplice = array.splice;
array.splice = function(index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
for (var _i2 = 0, deleted_1 = deleted; _i2 < deleted_1.length; _i2++) {
var item2 = deleted_1[_i2];
item2._resyncLighSource(_this);
}
return deleted;
};
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var item = array_1[_i];
item._resyncLighSource(this);
}
};
Light2.prototype._hookArrayForIncludedOnly = function(array) {
var _this = this;
var oldPush = array.push;
array.push = function() {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var result = oldPush.apply(array, items);
_this._resyncMeshes();
return result;
};
var oldSplice = array.splice;
array.splice = function(index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
_this._resyncMeshes();
return deleted;
};
this._resyncMeshes();
};
Light2.prototype._resyncMeshes = function() {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
mesh2._resyncLighSource(this);
}
};
Light2.prototype._markMeshesAsLightDirty = function() {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
if (mesh2._lightSources.indexOf(this) !== -1) {
mesh2._markSubMeshesAsLightDirty();
}
}
};
Light2.prototype._computePhotometricScale = function() {
this._photometricScale = this._getPhotometricScale();
this.getScene().resetCachedMaterial();
};
Light2.prototype._getPhotometricScale = function() {
var photometricScale = 0;
var lightTypeID = this.getTypeID();
var photometricMode = this.intensityMode;
if (photometricMode === Light2.INTENSITYMODE_AUTOMATIC) {
if (lightTypeID === Light2.LIGHTTYPEID_DIRECTIONALLIGHT) {
photometricMode = Light2.INTENSITYMODE_ILLUMINANCE;
} else {
photometricMode = Light2.INTENSITYMODE_LUMINOUSINTENSITY;
}
}
switch (lightTypeID) {
case Light2.LIGHTTYPEID_POINTLIGHT:
case Light2.LIGHTTYPEID_SPOTLIGHT:
switch (photometricMode) {
case Light2.INTENSITYMODE_LUMINOUSPOWER:
photometricScale = 1 / (4 * Math.PI);
break;
case Light2.INTENSITYMODE_LUMINOUSINTENSITY:
photometricScale = 1;
break;
case Light2.INTENSITYMODE_LUMINANCE:
photometricScale = this.radius * this.radius;
break;
}
break;
case Light2.LIGHTTYPEID_DIRECTIONALLIGHT:
switch (photometricMode) {
case Light2.INTENSITYMODE_ILLUMINANCE:
photometricScale = 1;
break;
case Light2.INTENSITYMODE_LUMINANCE:
var apexAngleRadians = this.radius;
apexAngleRadians = Math.max(apexAngleRadians, 1e-3);
var solidAngle = 2 * Math.PI * (1 - Math.cos(apexAngleRadians));
photometricScale = solidAngle;
break;
}
break;
case Light2.LIGHTTYPEID_HEMISPHERICLIGHT:
photometricScale = 1;
break;
}
return photometricScale;
};
Light2.prototype._reorderLightsInScene = function() {
var scene = this.getScene();
if (this._renderPriority != 0) {
scene.requireLightSorting = true;
}
this.getScene().sortLightsByPriority();
};
Light2.FALLOFF_DEFAULT = 0;
Light2.FALLOFF_PHYSICAL = 1;
Light2.FALLOFF_GLTF = 2;
Light2.FALLOFF_STANDARD = 3;
Light2.LIGHTMAP_DEFAULT = 0;
Light2.LIGHTMAP_SPECULAR = 1;
Light2.LIGHTMAP_SHADOWSONLY = 2;
Light2.INTENSITYMODE_AUTOMATIC = 0;
Light2.INTENSITYMODE_LUMINOUSPOWER = 1;
Light2.INTENSITYMODE_LUMINOUSINTENSITY = 2;
Light2.INTENSITYMODE_ILLUMINANCE = 3;
Light2.INTENSITYMODE_LUMINANCE = 4;
Light2.LIGHTTYPEID_POINTLIGHT = 0;
Light2.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
Light2.LIGHTTYPEID_SPOTLIGHT = 2;
Light2.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
__decorate([
BABYLON2.serializeAsColor3()
], Light2.prototype, "diffuse", void 0);
__decorate([
BABYLON2.serializeAsColor3()
], Light2.prototype, "specular", void 0);
__decorate([
BABYLON2.serialize()
], Light2.prototype, "falloffType", void 0);
__decorate([
BABYLON2.serialize()
], Light2.prototype, "intensity", void 0);
__decorate([
BABYLON2.serialize()
], Light2.prototype, "range", null);
__decorate([
BABYLON2.serialize()
], Light2.prototype, "intensityMode", null);
__decorate([
BABYLON2.serialize()
], Light2.prototype, "radius", null);
__decorate([
BABYLON2.serialize()
], Light2.prototype, "_renderPriority", void 0);
__decorate([
BABYLON2.expandToProperty("_reorderLightsInScene")
], Light2.prototype, "renderPriority", void 0);
__decorate([
BABYLON2.serialize("shadowEnabled")
], Light2.prototype, "_shadowEnabled", void 0);
__decorate([
BABYLON2.serialize("excludeWithLayerMask")
], Light2.prototype, "_excludeWithLayerMask", void 0);
__decorate([
BABYLON2.serialize("includeOnlyWithLayerMask")
], Light2.prototype, "_includeOnlyWithLayerMask", void 0);
__decorate([
BABYLON2.serialize("lightmapMode")
], Light2.prototype, "_lightmapMode", void 0);
return Light2;
}(BABYLON2.Node)
);
BABYLON2.Light = Light;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Camera = (
/** @class */
function(_super) {
__extends(Camera2, _super);
function Camera2(name, position, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) {
setActiveOnSceneIfNoneActive = true;
}
var _this = _super.call(this, name, scene) || this;
_this.upVector = BABYLON2.Vector3.Up();
_this.orthoLeft = null;
_this.orthoRight = null;
_this.orthoBottom = null;
_this.orthoTop = null;
_this.fov = 0.8;
_this.minZ = 1;
_this.maxZ = 1e4;
_this.inertia = 0.9;
_this.mode = Camera2.PERSPECTIVE_CAMERA;
_this.isIntermediate = false;
_this.viewport = new BABYLON2.Viewport(0, 0, 1, 1);
_this.layerMask = 268435455;
_this.fovMode = Camera2.FOVMODE_VERTICAL_FIXED;
_this.cameraRigMode = Camera2.RIG_MODE_NONE;
_this.customRenderTargets = new Array();
_this.onViewMatrixChangedObservable = new BABYLON2.Observable();
_this.onProjectionMatrixChangedObservable = new BABYLON2.Observable();
_this.onAfterCheckInputsObservable = new BABYLON2.Observable();
_this.onRestoreStateObservable = new BABYLON2.Observable();
_this._rigCameras = new Array();
_this._webvrViewMatrix = BABYLON2.Matrix.Identity();
_this._skipRendering = false;
_this._projectionMatrix = new BABYLON2.Matrix();
_this._postProcesses = new Array();
_this._activeMeshes = new BABYLON2.SmartArray(256);
_this._globalPosition = BABYLON2.Vector3.Zero();
_this._computedViewMatrix = BABYLON2.Matrix.Identity();
_this._doNotComputeProjectionMatrix = false;
_this._transformMatrix = BABYLON2.Matrix.Zero();
_this._refreshFrustumPlanes = true;
_this.autoClear = true;
_this.getScene().addCamera(_this);
if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
_this.getScene().activeCamera = _this;
}
_this.position = position;
return _this;
}
Camera2.prototype.storeState = function() {
this._stateStored = true;
this._storedFov = this.fov;
return this;
};
Camera2.prototype._restoreStateValues = function() {
if (!this._stateStored) {
return false;
}
this.fov = this._storedFov;
return true;
};
Camera2.prototype.restoreState = function() {
if (this._restoreStateValues()) {
this.onRestoreStateObservable.notifyObservers(this);
return true;
}
return false;
};
Camera2.prototype.getClassName = function() {
return "Camera";
};
Camera2.prototype.toString = function(fullDetails) {
var ret = "Name: " + this.name;
ret += ", type: " + this.getClassName();
if (this.animations) {
for (var i2 = 0; i2 < this.animations.length; i2++) {
ret += ", animation[0]: " + this.animations[i2].toString(fullDetails);
}
}
if (fullDetails) {
}
return ret;
};
Object.defineProperty(Camera2.prototype, "globalPosition", {
/**
* Gets the current world space position of the camera.
*/
get: function() {
return this._globalPosition;
},
enumerable: true,
configurable: true
});
Camera2.prototype.getActiveMeshes = function() {
return this._activeMeshes;
};
Camera2.prototype.isActiveMesh = function(mesh2) {
return this._activeMeshes.indexOf(mesh2) !== -1;
};
Camera2.prototype.isReady = function(completeCheck) {
if (completeCheck === void 0) {
completeCheck = false;
}
if (completeCheck) {
for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
var pp = _a[_i];
if (pp && !pp.isReady()) {
return false;
}
}
}
return _super.prototype.isReady.call(this, completeCheck);
};
Camera2.prototype._initCache = function() {
_super.prototype._initCache.call(this);
this._cache.position = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.upVector = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.mode = void 0;
this._cache.minZ = void 0;
this._cache.maxZ = void 0;
this._cache.fov = void 0;
this._cache.fovMode = void 0;
this._cache.aspectRatio = void 0;
this._cache.orthoLeft = void 0;
this._cache.orthoRight = void 0;
this._cache.orthoBottom = void 0;
this._cache.orthoTop = void 0;
this._cache.renderWidth = void 0;
this._cache.renderHeight = void 0;
};
Camera2.prototype._updateCache = function(ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
this._cache.position.copyFrom(this.position);
this._cache.upVector.copyFrom(this.upVector);
};
Camera2.prototype._isSynchronized = function() {
return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
};
Camera2.prototype._isSynchronizedViewMatrix = function() {
if (!_super.prototype._isSynchronized.call(this)) {
return false;
}
return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
};
Camera2.prototype._isSynchronizedProjectionMatrix = function() {
var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
if (!check) {
return false;
}
var engine = this.getEngine();
if (this.mode === Camera2.PERSPECTIVE_CAMERA) {
check = this._cache.fov === this.fov && this._cache.fovMode === this.fovMode && this._cache.aspectRatio === engine.getAspectRatio(this);
} else {
check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
}
return check;
};
Camera2.prototype.attachControl = function(element, noPreventDefault) {
};
Camera2.prototype.detachControl = function(element) {
};
Camera2.prototype.update = function() {
this._checkInputs();
if (this.cameraRigMode !== Camera2.RIG_MODE_NONE) {
this._updateRigCameras();
}
};
Camera2.prototype._checkInputs = function() {
this.onAfterCheckInputsObservable.notifyObservers(this);
};
Object.defineProperty(Camera2.prototype, "rigCameras", {
/** @hidden */
get: function() {
return this._rigCameras;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera2.prototype, "rigPostProcess", {
/**
* Gets the post process used by the rig cameras
*/
get: function() {
return this._rigPostProcess;
},
enumerable: true,
configurable: true
});
Camera2.prototype._getFirstPostProcess = function() {
for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
if (this._postProcesses[ppIndex] !== null) {
return this._postProcesses[ppIndex];
}
}
return null;
};
Camera2.prototype._cascadePostProcessesToRigCams = function() {
var firstPostProcess = this._getFirstPostProcess();
if (firstPostProcess) {
firstPostProcess.markTextureDirty();
}
for (var i2 = 0, len = this._rigCameras.length; i2 < len; i2++) {
var cam = this._rigCameras[i2];
var rigPostProcess = cam._rigPostProcess;
if (rigPostProcess) {
var isPass = rigPostProcess instanceof BABYLON2.PassPostProcess;
if (isPass) {
cam.isIntermediate = this._postProcesses.length === 0;
}
cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
rigPostProcess.markTextureDirty();
} else {
cam._postProcesses = this._postProcesses.slice(0);
}
}
};
Camera2.prototype.attachPostProcess = function(postProcess, insertAt) {
if (insertAt === void 0) {
insertAt = null;
}
if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
BABYLON2.Tools.Error("You're trying to reuse a post process not defined as reusable.");
return 0;
}
if (insertAt == null || insertAt < 0) {
this._postProcesses.push(postProcess);
} else if (this._postProcesses[insertAt] === null) {
this._postProcesses[insertAt] = postProcess;
} else {
this._postProcesses.splice(insertAt, 0, postProcess);
}
this._cascadePostProcessesToRigCams();
return this._postProcesses.indexOf(postProcess);
};
Camera2.prototype.detachPostProcess = function(postProcess) {
var idx = this._postProcesses.indexOf(postProcess);
if (idx !== -1) {
this._postProcesses[idx] = null;
}
this._cascadePostProcessesToRigCams();
};
Camera2.prototype.getWorldMatrix = function() {
if (this._isSynchronizedViewMatrix()) {
return this._worldMatrix;
}
this.getViewMatrix();
return this._worldMatrix;
};
Camera2.prototype._getViewMatrix = function() {
return BABYLON2.Matrix.Identity();
};
Camera2.prototype.getViewMatrix = function(force) {
if (!force && this._isSynchronizedViewMatrix()) {
return this._computedViewMatrix;
}
this.updateCache();
this._computedViewMatrix = this._getViewMatrix();
this._currentRenderId = this.getScene().getRenderId();
this._childRenderId = this._currentRenderId;
this._refreshFrustumPlanes = true;
if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
}
this.onViewMatrixChangedObservable.notifyObservers(this);
this._computedViewMatrix.invertToRef(this._worldMatrix);
return this._computedViewMatrix;
};
Camera2.prototype.freezeProjectionMatrix = function(projection) {
this._doNotComputeProjectionMatrix = true;
if (projection !== void 0) {
this._projectionMatrix = projection;
}
};
Camera2.prototype.unfreezeProjectionMatrix = function() {
this._doNotComputeProjectionMatrix = false;
};
Camera2.prototype.getProjectionMatrix = function(force) {
if (this._doNotComputeProjectionMatrix || !force && this._isSynchronizedProjectionMatrix()) {
return this._projectionMatrix;
}
this._cache.mode = this.mode;
this._cache.minZ = this.minZ;
this._cache.maxZ = this.maxZ;
this._refreshFrustumPlanes = true;
var engine = this.getEngine();
var scene = this.getScene();
if (this.mode === Camera2.PERSPECTIVE_CAMERA) {
this._cache.fov = this.fov;
this._cache.fovMode = this.fovMode;
this._cache.aspectRatio = engine.getAspectRatio(this);
if (this.minZ <= 0) {
this.minZ = 0.1;
}
if (scene.useRightHandedSystem) {
BABYLON2.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera2.FOVMODE_VERTICAL_FIXED);
} else {
BABYLON2.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera2.FOVMODE_VERTICAL_FIXED);
}
} else {
var halfWidth = engine.getRenderWidth() / 2;
var halfHeight = engine.getRenderHeight() / 2;
if (scene.useRightHandedSystem) {
BABYLON2.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
} else {
BABYLON2.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
}
this._cache.orthoLeft = this.orthoLeft;
this._cache.orthoRight = this.orthoRight;
this._cache.orthoBottom = this.orthoBottom;
this._cache.orthoTop = this.orthoTop;
this._cache.renderWidth = engine.getRenderWidth();
this._cache.renderHeight = engine.getRenderHeight();
}
this.onProjectionMatrixChangedObservable.notifyObservers(this);
return this._projectionMatrix;
};
Camera2.prototype.getTransformationMatrix = function() {
this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
return this._transformMatrix;
};
Camera2.prototype._updateFrustumPlanes = function() {
if (!this._refreshFrustumPlanes) {
return;
}
this.getTransformationMatrix();
if (!this._frustumPlanes) {
this._frustumPlanes = BABYLON2.Frustum.GetPlanes(this._transformMatrix);
} else {
BABYLON2.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
}
this._refreshFrustumPlanes = false;
};
Camera2.prototype.isInFrustum = function(target) {
this._updateFrustumPlanes();
return target.isInFrustum(this._frustumPlanes);
};
Camera2.prototype.isCompletelyInFrustum = function(target) {
this._updateFrustumPlanes();
return target.isCompletelyInFrustum(this._frustumPlanes);
};
Camera2.prototype.getForwardRay = function(length, transform, origin) {
if (length === void 0) {
length = 100;
}
if (!transform) {
transform = this.getWorldMatrix();
}
if (!origin) {
origin = this.position;
}
var forward = this._scene.useRightHandedSystem ? new BABYLON2.Vector3(0, 0, -1) : new BABYLON2.Vector3(0, 0, 1);
var forwardWorld = BABYLON2.Vector3.TransformNormal(forward, transform);
var direction = BABYLON2.Vector3.Normalize(forwardWorld);
return new BABYLON2.Ray(origin, direction, length);
};
Camera2.prototype.dispose = function(doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) {
disposeMaterialAndTextures = false;
}
this.onViewMatrixChangedObservable.clear();
this.onProjectionMatrixChangedObservable.clear();
this.onAfterCheckInputsObservable.clear();
this.onRestoreStateObservable.clear();
if (this.inputs) {
this.inputs.clear();
}
this.getScene().stopAnimation(this);
this.getScene().removeCamera(this);
while (this._rigCameras.length > 0) {
var camera2 = this._rigCameras.pop();
if (camera2) {
camera2.dispose();
}
}
if (this._rigPostProcess) {
this._rigPostProcess.dispose(this);
this._rigPostProcess = null;
this._postProcesses = [];
} else if (this.cameraRigMode !== Camera2.RIG_MODE_NONE) {
this._rigPostProcess = null;
this._postProcesses = [];
} else {
var i2 = this._postProcesses.length;
while (--i2 >= 0) {
var postProcess = this._postProcesses[i2];
if (postProcess) {
postProcess.dispose(this);
}
}
}
var i2 = this.customRenderTargets.length;
while (--i2 >= 0) {
this.customRenderTargets[i2].dispose();
}
this.customRenderTargets = [];
this._activeMeshes.dispose();
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
Object.defineProperty(Camera2.prototype, "leftCamera", {
/**
* Gets the left camera of a rig setup in case of Rigged Camera
*/
get: function() {
if (this._rigCameras.length < 1) {
return null;
}
return this._rigCameras[0];
},
enumerable: true,
configurable: true
});
Object.defineProperty(Camera2.prototype, "rightCamera", {
/**
* Gets the right camera of a rig setup in case of Rigged Camera
*/
get: function() {
if (this._rigCameras.length < 2) {
return null;
}
return this._rigCameras[1];
},
enumerable: true,
configurable: true
});
Camera2.prototype.getLeftTarget = function() {
if (this._rigCameras.length < 1) {
return null;
}
return this._rigCameras[0].getTarget();
};
Camera2.prototype.getRightTarget = function() {
if (this._rigCameras.length < 2) {
return null;
}
return this._rigCameras[1].getTarget();
};
Camera2.prototype.setCameraRigMode = function(mode, rigParams) {
if (this.cameraRigMode === mode) {
return;
}
while (this._rigCameras.length > 0) {
var camera2 = this._rigCameras.pop();
if (camera2) {
camera2.dispose();
}
}
this.cameraRigMode = mode;
this._cameraRigParams = {};
this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
this._cameraRigParams.stereoHalfAngle = BABYLON2.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
if (this.cameraRigMode !== Camera2.RIG_MODE_NONE) {
var leftCamera = this.createRigCamera(this.name + "_L", 0);
var rightCamera = this.createRigCamera(this.name + "_R", 1);
if (leftCamera && rightCamera) {
this._rigCameras.push(leftCamera);
this._rigCameras.push(rightCamera);
}
}
switch (this.cameraRigMode) {
case Camera2.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
this._rigCameras[0]._rigPostProcess = new BABYLON2.PassPostProcess(this.name + "_passthru", 1, this._rigCameras[0]);
this._rigCameras[1]._rigPostProcess = new BABYLON2.AnaglyphPostProcess(this.name + "_anaglyph", 1, this._rigCameras);
break;
case Camera2.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case Camera2.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
case Camera2.RIG_MODE_STEREOSCOPIC_OVERUNDER:
var isStereoscopicHoriz = this.cameraRigMode === Camera2.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera2.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
this._rigCameras[0]._rigPostProcess = new BABYLON2.PassPostProcess(this.name + "_passthru", 1, this._rigCameras[0]);
this._rigCameras[1]._rigPostProcess = new BABYLON2.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
break;
case Camera2.RIG_MODE_VR:
var metrics = rigParams.vrCameraMetrics || BABYLON2.VRCameraMetrics.GetDefault();
this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
this._rigCameras[0].viewport = new BABYLON2.Viewport(0, 0, 0.5, 1);
this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON2.Matrix();
this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
this._rigCameras[1].viewport = new BABYLON2.Viewport(0.5, 0, 0.5, 1);
this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON2.Matrix();
this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
if (metrics.compensateDistortion) {
this._rigCameras[0]._rigPostProcess = new BABYLON2.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
this._rigCameras[1]._rigPostProcess = new BABYLON2.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
}
break;
case Camera2.RIG_MODE_WEBVR:
if (rigParams.vrDisplay) {
var leftEye = rigParams.vrDisplay.getEyeParameters("left");
var rightEye = rigParams.vrDisplay.getEyeParameters("right");
this._rigCameras[0].viewport = new BABYLON2.Viewport(0, 0, 0.5, 1);
this._rigCameras[0].setCameraRigParameter("left", true);
this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON2.Matrix();
this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
this._rigCameras[0].parent = this;
this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
this._rigCameras[1].viewport = new BABYLON2.Viewport(0.5, 0, 0.5, 1);
this._rigCameras[1].setCameraRigParameter("eyeParameters", rightEye);
this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON2.Matrix();
this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
this._rigCameras[1].parent = this;
this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
if (Camera2.UseAlternateWebVRRendering) {
this._rigCameras[1]._skipRendering = true;
this._rigCameras[0]._alternateCamera = this._rigCameras[1];
}
}
break;
}
this._cascadePostProcessesToRigCams();
this.update();
};
Camera2.prototype._getVRProjectionMatrix = function() {
BABYLON2.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
return this._projectionMatrix;
};
Camera2.prototype._updateCameraRotationMatrix = function() {
};
Camera2.prototype._updateWebVRCameraRotationMatrix = function() {
};
Camera2.prototype._getWebVRProjectionMatrix = function() {
return BABYLON2.Matrix.Identity();
};
Camera2.prototype._getWebVRViewMatrix = function() {
return BABYLON2.Matrix.Identity();
};
Camera2.prototype.setCameraRigParameter = function(name, value) {
if (!this._cameraRigParams) {
this._cameraRigParams = {};
}
this._cameraRigParams[name] = value;
if (name === "interaxialDistance") {
this._cameraRigParams.stereoHalfAngle = BABYLON2.Tools.ToRadians(value / 0.0637);
}
};
Camera2.prototype.createRigCamera = function(name, cameraIndex) {
return null;
};
Camera2.prototype._updateRigCameras = function() {
for (var i2 = 0; i2 < this._rigCameras.length; i2++) {
this._rigCameras[i2].minZ = this.minZ;
this._rigCameras[i2].maxZ = this.maxZ;
this._rigCameras[i2].fov = this.fov;
}
if (this.cameraRigMode === Camera2.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
}
};
Camera2.prototype._setupInputs = function() {
};
Camera2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.type = this.getClassName();
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
if (this.inputs) {
this.inputs.serialize(serializationObject);
}
BABYLON2.Animation.AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
return serializationObject;
};
Camera2.prototype.clone = function(name) {
return BABYLON2.SerializationHelper.Clone(Camera2.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
};
Camera2.prototype.getDirection = function(localAxis) {
var result = BABYLON2.Vector3.Zero();
this.getDirectionToRef(localAxis, result);
return result;
};
Camera2.prototype.getDirectionToRef = function(localAxis, result) {
BABYLON2.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
};
Camera2.GetConstructorFromName = function(type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
if (interaxial_distance === void 0) {
interaxial_distance = 0;
}
if (isStereoscopicSideBySide === void 0) {
isStereoscopicSideBySide = true;
}
var constructorFunc = BABYLON2.Node.Construct(type, name, scene, {
interaxial_distance,
isStereoscopicSideBySide
});
if (constructorFunc) {
return constructorFunc;
}
return function() {
return new BABYLON2.UniversalCamera(name, BABYLON2.Vector3.Zero(), scene);
};
};
Camera2.prototype.computeWorldMatrix = function() {
return this.getWorldMatrix();
};
Camera2.Parse = function(parsedCamera, scene) {
var type = parsedCamera.type;
var construct = Camera2.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
var camera2 = BABYLON2.SerializationHelper.Parse(construct, parsedCamera, scene);
if (parsedCamera.parentId) {
camera2._waitingParentId = parsedCamera.parentId;
}
if (camera2.inputs) {
camera2.inputs.parse(parsedCamera);
camera2._setupInputs();
}
if (camera2.setPosition) {
camera2.position.copyFromFloats(0, 0, 0);
camera2.setPosition(BABYLON2.Vector3.FromArray(parsedCamera.position));
}
if (parsedCamera.target) {
if (camera2.setTarget) {
camera2.setTarget(BABYLON2.Vector3.FromArray(parsedCamera.target));
}
}
if (parsedCamera.cameraRigMode) {
var rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
camera2.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
}
if (parsedCamera.animations) {
for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
var parsedAnimation = parsedCamera.animations[animationIndex];
camera2.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
BABYLON2.Node.ParseAnimationRanges(camera2, parsedCamera, scene);
}
if (parsedCamera.autoAnimate) {
scene.beginAnimation(camera2, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1);
}
return camera2;
};
Camera2.PERSPECTIVE_CAMERA = 0;
Camera2.ORTHOGRAPHIC_CAMERA = 1;
Camera2.FOVMODE_VERTICAL_FIXED = 0;
Camera2.FOVMODE_HORIZONTAL_FIXED = 1;
Camera2.RIG_MODE_NONE = 0;
Camera2.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
Camera2.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
Camera2.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
Camera2.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
Camera2.RIG_MODE_VR = 20;
Camera2.RIG_MODE_WEBVR = 21;
Camera2.ForceAttachControlToAlwaysPreventDefault = false;
Camera2.UseAlternateWebVRRendering = false;
__decorate([
BABYLON2.serializeAsVector3()
], Camera2.prototype, "position", void 0);
__decorate([
BABYLON2.serializeAsVector3()
], Camera2.prototype, "upVector", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "orthoLeft", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "orthoRight", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "orthoBottom", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "orthoTop", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "fov", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "minZ", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "maxZ", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "inertia", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "mode", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "layerMask", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "fovMode", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "cameraRigMode", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "interaxialDistance", void 0);
__decorate([
BABYLON2.serialize()
], Camera2.prototype, "isStereoscopicSideBySide", void 0);
return Camera2;
}(BABYLON2.Node)
);
BABYLON2.Camera = Camera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RenderingManager = (
/** @class */
function() {
function RenderingManager2(scene) {
this._useSceneAutoClearSetup = false;
this._renderingGroups = new Array();
this._autoClearDepthStencil = {};
this._customOpaqueSortCompareFn = {};
this._customAlphaTestSortCompareFn = {};
this._customTransparentSortCompareFn = {};
this._renderingGroupInfo = new BABYLON2.RenderingGroupInfo();
this._scene = scene;
for (var i2 = RenderingManager2.MIN_RENDERINGGROUPS; i2 < RenderingManager2.MAX_RENDERINGGROUPS; i2++) {
this._autoClearDepthStencil[i2] = { autoClear: true, depth: true, stencil: true };
}
}
RenderingManager2.prototype._clearDepthStencilBuffer = function(depth, stencil) {
if (depth === void 0) {
depth = true;
}
if (stencil === void 0) {
stencil = true;
}
if (this._depthStencilBufferAlreadyCleaned) {
return;
}
this._scene.getEngine().clear(null, false, depth, stencil);
this._depthStencilBufferAlreadyCleaned = true;
};
RenderingManager2.prototype.render = function(customRenderFunction, activeMeshes, renderParticles, renderSprites) {
var info = this._renderingGroupInfo;
info.scene = this._scene;
info.camera = this._scene.activeCamera;
if (this._scene.spriteManagers && renderSprites) {
for (var index = 0; index < this._scene.spriteManagers.length; index++) {
var manager = this._scene.spriteManagers[index];
this.dispatchSprites(manager);
}
}
for (var index = RenderingManager2.MIN_RENDERINGGROUPS; index < RenderingManager2.MAX_RENDERINGGROUPS; index++) {
this._depthStencilBufferAlreadyCleaned = index === RenderingManager2.MIN_RENDERINGGROUPS;
var renderingGroup = this._renderingGroups[index];
if (!renderingGroup) {
continue;
}
var renderingGroupMask = Math.pow(2, index);
info.renderingGroupId = index;
this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
if (RenderingManager2.AUTOCLEAR) {
var autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index];
if (autoClear && autoClear.autoClear) {
this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
}
}
for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
var step = _a[_i];
step.action(index);
}
renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
var step = _c[_b];
step.action(index);
}
this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
}
};
RenderingManager2.prototype.reset = function() {
for (var index = RenderingManager2.MIN_RENDERINGGROUPS; index < RenderingManager2.MAX_RENDERINGGROUPS; index++) {
var renderingGroup = this._renderingGroups[index];
if (renderingGroup) {
renderingGroup.prepare();
}
}
};
RenderingManager2.prototype.dispose = function() {
this.freeRenderingGroups();
this._renderingGroups.length = 0;
this._renderingGroupInfo = null;
};
RenderingManager2.prototype.freeRenderingGroups = function() {
for (var index = RenderingManager2.MIN_RENDERINGGROUPS; index < RenderingManager2.MAX_RENDERINGGROUPS; index++) {
var renderingGroup = this._renderingGroups[index];
if (renderingGroup) {
renderingGroup.dispose();
}
}
};
RenderingManager2.prototype._prepareRenderingGroup = function(renderingGroupId) {
if (this._renderingGroups[renderingGroupId] === void 0) {
this._renderingGroups[renderingGroupId] = new BABYLON2.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
}
};
RenderingManager2.prototype.dispatchSprites = function(spriteManager) {
var renderingGroupId = spriteManager.renderingGroupId || 0;
this._prepareRenderingGroup(renderingGroupId);
this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
};
RenderingManager2.prototype.dispatchParticles = function(particleSystem) {
var renderingGroupId = particleSystem.renderingGroupId || 0;
this._prepareRenderingGroup(renderingGroupId);
this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
};
RenderingManager2.prototype.dispatch = function(subMesh, mesh2, material) {
if (mesh2 === void 0) {
mesh2 = subMesh.getMesh();
}
var renderingGroupId = mesh2.renderingGroupId || 0;
this._prepareRenderingGroup(renderingGroupId);
this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh2, material);
};
RenderingManager2.prototype.setRenderingOrder = function(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
if (opaqueSortCompareFn === void 0) {
opaqueSortCompareFn = null;
}
if (alphaTestSortCompareFn === void 0) {
alphaTestSortCompareFn = null;
}
if (transparentSortCompareFn === void 0) {
transparentSortCompareFn = null;
}
this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
if (this._renderingGroups[renderingGroupId]) {
var group = this._renderingGroups[renderingGroupId];
group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
}
};
RenderingManager2.prototype.setRenderingAutoClearDepthStencil = function(renderingGroupId, autoClearDepthStencil, depth, stencil) {
if (depth === void 0) {
depth = true;
}
if (stencil === void 0) {
stencil = true;
}
this._autoClearDepthStencil[renderingGroupId] = {
autoClear: autoClearDepthStencil,
depth,
stencil
};
};
RenderingManager2.prototype.getAutoClearDepthStencilSetup = function(index) {
return this._autoClearDepthStencil[index];
};
RenderingManager2.MAX_RENDERINGGROUPS = 4;
RenderingManager2.MIN_RENDERINGGROUPS = 0;
RenderingManager2.AUTOCLEAR = true;
return RenderingManager2;
}()
);
BABYLON2.RenderingManager = RenderingManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RenderingGroup = (
/** @class */
function() {
function RenderingGroup2(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
if (opaqueSortCompareFn === void 0) {
opaqueSortCompareFn = null;
}
if (alphaTestSortCompareFn === void 0) {
alphaTestSortCompareFn = null;
}
if (transparentSortCompareFn === void 0) {
transparentSortCompareFn = null;
}
this.index = index;
this._opaqueSubMeshes = new BABYLON2.SmartArray(256);
this._transparentSubMeshes = new BABYLON2.SmartArray(256);
this._alphaTestSubMeshes = new BABYLON2.SmartArray(256);
this._depthOnlySubMeshes = new BABYLON2.SmartArray(256);
this._particleSystems = new BABYLON2.SmartArray(256);
this._spriteManagers = new BABYLON2.SmartArray(256);
this._edgesRenderers = new BABYLON2.SmartArray(16);
this._scene = scene;
this.opaqueSortCompareFn = opaqueSortCompareFn;
this.alphaTestSortCompareFn = alphaTestSortCompareFn;
this.transparentSortCompareFn = transparentSortCompareFn;
}
Object.defineProperty(RenderingGroup2.prototype, "opaqueSortCompareFn", {
/**
* Set the opaque sort comparison function.
* If null the sub meshes will be render in the order they were created
*/
set: function(value) {
this._opaqueSortCompareFn = value;
if (value) {
this._renderOpaque = this.renderOpaqueSorted;
} else {
this._renderOpaque = RenderingGroup2.renderUnsorted;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderingGroup2.prototype, "alphaTestSortCompareFn", {
/**
* Set the alpha test sort comparison function.
* If null the sub meshes will be render in the order they were created
*/
set: function(value) {
this._alphaTestSortCompareFn = value;
if (value) {
this._renderAlphaTest = this.renderAlphaTestSorted;
} else {
this._renderAlphaTest = RenderingGroup2.renderUnsorted;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderingGroup2.prototype, "transparentSortCompareFn", {
/**
* Set the transparent sort comparison function.
* If null the sub meshes will be render in the order they were created
*/
set: function(value) {
if (value) {
this._transparentSortCompareFn = value;
} else {
this._transparentSortCompareFn = RenderingGroup2.defaultTransparentSortCompare;
}
this._renderTransparent = this.renderTransparentSorted;
},
enumerable: true,
configurable: true
});
RenderingGroup2.prototype.render = function(customRenderFunction, renderSprites, renderParticles, activeMeshes) {
if (customRenderFunction) {
customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
return;
}
var engine = this._scene.getEngine();
if (this._depthOnlySubMeshes.length !== 0) {
engine.setColorWrite(false);
this._renderAlphaTest(this._depthOnlySubMeshes);
engine.setColorWrite(true);
}
if (this._opaqueSubMeshes.length !== 0) {
this._renderOpaque(this._opaqueSubMeshes);
}
if (this._alphaTestSubMeshes.length !== 0) {
this._renderAlphaTest(this._alphaTestSubMeshes);
}
var stencilState = engine.getStencilBuffer();
engine.setStencilBuffer(false);
if (renderSprites) {
this._renderSprites();
}
if (renderParticles) {
this._renderParticles(activeMeshes);
}
if (this.onBeforeTransparentRendering) {
this.onBeforeTransparentRendering();
}
if (this._transparentSubMeshes.length !== 0) {
this._renderTransparent(this._transparentSubMeshes);
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
}
engine.setStencilBuffer(false);
if (this._edgesRenderers.length) {
for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
this._edgesRenderers.data[edgesRendererIndex].render();
}
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
}
engine.setStencilBuffer(stencilState);
};
RenderingGroup2.prototype.renderOpaqueSorted = function(subMeshes) {
return RenderingGroup2.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
};
RenderingGroup2.prototype.renderAlphaTestSorted = function(subMeshes) {
return RenderingGroup2.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
};
RenderingGroup2.prototype.renderTransparentSorted = function(subMeshes) {
return RenderingGroup2.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
};
RenderingGroup2.renderSorted = function(subMeshes, sortCompareFn, camera2, transparent) {
var subIndex = 0;
var subMesh;
var cameraPosition = camera2 ? camera2.globalPosition : BABYLON2.Vector3.Zero();
for (; subIndex < subMeshes.length; subIndex++) {
subMesh = subMeshes.data[subIndex];
subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
}
var sortedArray = subMeshes.data.slice(0, subMeshes.length);
if (sortCompareFn) {
sortedArray.sort(sortCompareFn);
}
for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
subMesh = sortedArray[subIndex];
if (transparent) {
var material = subMesh.getMaterial();
if (material && material.needDepthPrePass) {
var engine = material.getScene().getEngine();
engine.setColorWrite(false);
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
subMesh.render(false);
engine.setColorWrite(true);
}
}
subMesh.render(transparent);
}
};
RenderingGroup2.renderUnsorted = function(subMeshes) {
for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
var submesh = subMeshes.data[subIndex];
submesh.render(false);
}
};
RenderingGroup2.defaultTransparentSortCompare = function(a, b2) {
if (a._alphaIndex > b2._alphaIndex) {
return 1;
}
if (a._alphaIndex < b2._alphaIndex) {
return -1;
}
return RenderingGroup2.backToFrontSortCompare(a, b2);
};
RenderingGroup2.backToFrontSortCompare = function(a, b2) {
if (a._distanceToCamera < b2._distanceToCamera) {
return 1;
}
if (a._distanceToCamera > b2._distanceToCamera) {
return -1;
}
return 0;
};
RenderingGroup2.frontToBackSortCompare = function(a, b2) {
if (a._distanceToCamera < b2._distanceToCamera) {
return -1;
}
if (a._distanceToCamera > b2._distanceToCamera) {
return 1;
}
return 0;
};
RenderingGroup2.prototype.prepare = function() {
this._opaqueSubMeshes.reset();
this._transparentSubMeshes.reset();
this._alphaTestSubMeshes.reset();
this._depthOnlySubMeshes.reset();
this._particleSystems.reset();
this._spriteManagers.reset();
this._edgesRenderers.reset();
};
RenderingGroup2.prototype.dispose = function() {
this._opaqueSubMeshes.dispose();
this._transparentSubMeshes.dispose();
this._alphaTestSubMeshes.dispose();
this._depthOnlySubMeshes.dispose();
this._particleSystems.dispose();
this._spriteManagers.dispose();
this._edgesRenderers.dispose();
};
RenderingGroup2.prototype.dispatch = function(subMesh, mesh2, material) {
if (mesh2 === void 0) {
mesh2 = subMesh.getMesh();
}
if (material === void 0) {
material = subMesh.getMaterial();
}
if (material === null || material === void 0) {
return;
}
if (material.needAlphaBlendingForMesh(mesh2)) {
this._transparentSubMeshes.push(subMesh);
} else if (material.needAlphaTesting()) {
if (material.needDepthPrePass) {
this._depthOnlySubMeshes.push(subMesh);
}
this._alphaTestSubMeshes.push(subMesh);
} else {
if (material.needDepthPrePass) {
this._depthOnlySubMeshes.push(subMesh);
}
this._opaqueSubMeshes.push(subMesh);
}
if (mesh2._edgesRenderer && mesh2._edgesRenderer.isEnabled) {
this._edgesRenderers.push(mesh2._edgesRenderer);
}
};
RenderingGroup2.prototype.dispatchSprites = function(spriteManager) {
this._spriteManagers.push(spriteManager);
};
RenderingGroup2.prototype.dispatchParticles = function(particleSystem) {
this._particleSystems.push(particleSystem);
};
RenderingGroup2.prototype._renderParticles = function(activeMeshes) {
if (this._particleSystems.length === 0) {
return;
}
var activeCamera = this._scene.activeCamera;
this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
var particleSystem = this._particleSystems.data[particleIndex];
if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
continue;
}
var emitter = particleSystem.emitter;
if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
this._scene._activeParticles.addCount(particleSystem.render(), false);
}
}
this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
};
RenderingGroup2.prototype._renderSprites = function() {
if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
return;
}
var activeCamera = this._scene.activeCamera;
this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
for (var id = 0; id < this._spriteManagers.length; id++) {
var spriteManager = this._spriteManagers.data[id];
if ((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0) {
spriteManager.render();
}
}
this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
};
return RenderingGroup2;
}()
);
BABYLON2.RenderingGroup = RenderingGroup;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SceneComponentConstants = (
/** @class */
function() {
function SceneComponentConstants2() {
}
SceneComponentConstants2.NAME_EFFECTLAYER = "EffectLayer";
SceneComponentConstants2.NAME_LAYER = "Layer";
SceneComponentConstants2.NAME_LENSFLARESYSTEM = "LensFlareSystem";
SceneComponentConstants2.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
SceneComponentConstants2.NAME_PARTICLESYSTEM = "ParticleSystem";
SceneComponentConstants2.NAME_GAMEPAD = "Gamepad";
SceneComponentConstants2.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
SceneComponentConstants2.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
SceneComponentConstants2.NAME_DEPTHRENDERER = "DepthRenderer";
SceneComponentConstants2.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
SceneComponentConstants2.NAME_SPRITE = "Sprite";
SceneComponentConstants2.NAME_OUTLINERENDERER = "Outline";
SceneComponentConstants2.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
SceneComponentConstants2.NAME_SHADOWGENERATOR = "ShadowGenerator";
SceneComponentConstants2.NAME_OCTREE = "Octree";
SceneComponentConstants2.NAME_PHYSICSENGINE = "PhysicsEngine";
SceneComponentConstants2.NAME_AUDIO = "Audio";
SceneComponentConstants2.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
SceneComponentConstants2.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
SceneComponentConstants2.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
SceneComponentConstants2.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
SceneComponentConstants2.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
SceneComponentConstants2.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
SceneComponentConstants2.STEP_BEFORECAMERADRAW_LAYER = 1;
SceneComponentConstants2.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
SceneComponentConstants2.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
SceneComponentConstants2.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
SceneComponentConstants2.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
SceneComponentConstants2.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
SceneComponentConstants2.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
SceneComponentConstants2.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
SceneComponentConstants2.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
SceneComponentConstants2.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
SceneComponentConstants2.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
SceneComponentConstants2.STEP_AFTERCAMERADRAW_LAYER = 3;
SceneComponentConstants2.STEP_AFTERRENDER_AUDIO = 0;
SceneComponentConstants2.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
SceneComponentConstants2.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
SceneComponentConstants2.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
SceneComponentConstants2.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
SceneComponentConstants2.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
SceneComponentConstants2.STEP_POINTERMOVE_SPRITE = 0;
SceneComponentConstants2.STEP_POINTERDOWN_SPRITE = 0;
SceneComponentConstants2.STEP_POINTERUP_SPRITE = 0;
return SceneComponentConstants2;
}()
);
BABYLON2.SceneComponentConstants = SceneComponentConstants;
var Stage = (
/** @class */
function(_super) {
__extends(Stage2, _super);
function Stage2(items) {
return _super.apply(this, items) || this;
}
Stage2.Create = function() {
return Object.create(Stage2.prototype);
};
Stage2.prototype.registerStep = function(index, component, action) {
var i2 = 0;
var maxIndex = Number.MAX_VALUE;
for (; i2 < this.length; i2++) {
var step = this[i2];
maxIndex = step.index;
if (index < maxIndex) {
break;
}
}
this.splice(i2, 0, { index, component, action: action.bind(component) });
};
Stage2.prototype.clear = function() {
this.length = 0;
};
return Stage2;
}(Array)
);
BABYLON2.Stage = Stage;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var AbstractScene = (
/** @class */
function() {
function AbstractScene2() {
this.rootNodes = new Array();
this.cameras = new Array();
this.lights = new Array();
this.meshes = new Array();
this.skeletons = new Array();
this.particleSystems = new Array();
this.animations = [];
this.animationGroups = new Array();
this.multiMaterials = new Array();
this.materials = new Array();
this.morphTargetManagers = new Array();
this.geometries = new Array();
this.transformNodes = new Array();
this.actionManagers = new Array();
this.textures = new Array();
}
AbstractScene2.AddParser = function(name, parser) {
this._BabylonFileParsers[name] = parser;
};
AbstractScene2.GetParser = function(name) {
if (this._BabylonFileParsers[name]) {
return this._BabylonFileParsers[name];
}
return null;
};
AbstractScene2.AddIndividualParser = function(name, parser) {
this._IndividualBabylonFileParsers[name] = parser;
};
AbstractScene2.GetIndividualParser = function(name) {
if (this._IndividualBabylonFileParsers[name]) {
return this._IndividualBabylonFileParsers[name];
}
return null;
};
AbstractScene2.Parse = function(jsonData, scene, container, rootUrl) {
for (var parserName in this._BabylonFileParsers) {
if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
}
}
};
AbstractScene2._BabylonFileParsers = {};
AbstractScene2._IndividualBabylonFileParsers = {};
return AbstractScene2;
}()
);
BABYLON2.AbstractScene = AbstractScene;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ClickInfo = (
/** @class */
function() {
function ClickInfo2() {
this._singleClick = false;
this._doubleClick = false;
this._hasSwiped = false;
this._ignore = false;
}
Object.defineProperty(ClickInfo2.prototype, "singleClick", {
get: function() {
return this._singleClick;
},
set: function(b2) {
this._singleClick = b2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ClickInfo2.prototype, "doubleClick", {
get: function() {
return this._doubleClick;
},
set: function(b2) {
this._doubleClick = b2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ClickInfo2.prototype, "hasSwiped", {
get: function() {
return this._hasSwiped;
},
set: function(b2) {
this._hasSwiped = b2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ClickInfo2.prototype, "ignore", {
get: function() {
return this._ignore;
},
set: function(b2) {
this._ignore = b2;
},
enumerable: true,
configurable: true
});
return ClickInfo2;
}()
);
var RenderingGroupInfo = (
/** @class */
function() {
function RenderingGroupInfo2() {
}
return RenderingGroupInfo2;
}()
);
BABYLON2.RenderingGroupInfo = RenderingGroupInfo;
var Scene = (
/** @class */
function(_super) {
__extends(Scene2, _super);
function Scene2(engine) {
var _this = _super.call(this) || this;
_this.autoClear = true;
_this.autoClearDepthAndStencil = true;
_this.clearColor = new BABYLON2.Color4(0.2, 0.2, 0.3, 1);
_this.ambientColor = new BABYLON2.Color3(0, 0, 0);
_this._forceWireframe = false;
_this._forcePointsCloud = false;
_this.animationsEnabled = true;
_this._animationPropertiesOverride = null;
_this.useConstantAnimationDeltaTime = false;
_this.constantlyUpdateMeshUnderPointer = false;
_this.hoverCursor = "pointer";
_this.defaultCursor = "";
_this.preventDefaultOnPointerDown = true;
_this.metadata = null;
_this.disableOfflineSupportExceptionRules = new Array();
_this.onDisposeObservable = new BABYLON2.Observable();
_this._onDisposeObserver = null;
_this.onBeforeRenderObservable = new BABYLON2.Observable();
_this._onBeforeRenderObserver = null;
_this.onAfterRenderObservable = new BABYLON2.Observable();
_this._onAfterRenderObserver = null;
_this.onBeforeAnimationsObservable = new BABYLON2.Observable();
_this.onAfterAnimationsObservable = new BABYLON2.Observable();
_this.onBeforeDrawPhaseObservable = new BABYLON2.Observable();
_this.onAfterDrawPhaseObservable = new BABYLON2.Observable();
_this.onReadyObservable = new BABYLON2.Observable();
_this.onBeforeCameraRenderObservable = new BABYLON2.Observable();
_this._onBeforeCameraRenderObserver = null;
_this.onAfterCameraRenderObservable = new BABYLON2.Observable();
_this._onAfterCameraRenderObserver = null;
_this.onBeforeActiveMeshesEvaluationObservable = new BABYLON2.Observable();
_this.onAfterActiveMeshesEvaluationObservable = new BABYLON2.Observable();
_this.onBeforeParticlesRenderingObservable = new BABYLON2.Observable();
_this.onAfterParticlesRenderingObservable = new BABYLON2.Observable();
_this.onDataLoadedObservable = new BABYLON2.Observable();
_this.onNewCameraAddedObservable = new BABYLON2.Observable();
_this.onCameraRemovedObservable = new BABYLON2.Observable();
_this.onNewLightAddedObservable = new BABYLON2.Observable();
_this.onLightRemovedObservable = new BABYLON2.Observable();
_this.onNewGeometryAddedObservable = new BABYLON2.Observable();
_this.onGeometryRemovedObservable = new BABYLON2.Observable();
_this.onNewTransformNodeAddedObservable = new BABYLON2.Observable();
_this.onTransformNodeRemovedObservable = new BABYLON2.Observable();
_this.onNewMeshAddedObservable = new BABYLON2.Observable();
_this.onMeshRemovedObservable = new BABYLON2.Observable();
_this.onNewMaterialAddedObservable = new BABYLON2.Observable();
_this.onMaterialRemovedObservable = new BABYLON2.Observable();
_this.onNewTextureAddedObservable = new BABYLON2.Observable();
_this.onTextureRemovedObservable = new BABYLON2.Observable();
_this.onBeforeRenderTargetsRenderObservable = new BABYLON2.Observable();
_this.onAfterRenderTargetsRenderObservable = new BABYLON2.Observable();
_this.onBeforeStepObservable = new BABYLON2.Observable();
_this.onAfterStepObservable = new BABYLON2.Observable();
_this.onBeforeRenderingGroupObservable = new BABYLON2.Observable();
_this.onAfterRenderingGroupObservable = new BABYLON2.Observable();
_this.onMeshImportedObservable = new BABYLON2.Observable();
_this._registeredForLateAnimationBindings = new BABYLON2.SmartArrayNoDuplicate(256);
_this.onPrePointerObservable = new BABYLON2.Observable();
_this.onPointerObservable = new BABYLON2.Observable();
_this._meshPickProceed = false;
_this._currentPickResult = null;
_this._previousPickResult = null;
_this._totalPointersPressed = 0;
_this._doubleClickOccured = false;
_this.cameraToUseForPointers = null;
_this._pointerX = 0;
_this._pointerY = 0;
_this._startingPointerPosition = new BABYLON2.Vector2(0, 0);
_this._previousStartingPointerPosition = new BABYLON2.Vector2(0, 0);
_this._startingPointerTime = 0;
_this._previousStartingPointerTime = 0;
_this._pointerCaptures = {};
_this._timeAccumulator = 0;
_this._currentStepId = 0;
_this._currentInternalStep = 0;
_this.onPreKeyboardObservable = new BABYLON2.Observable();
_this.onKeyboardObservable = new BABYLON2.Observable();
_this._useRightHandedSystem = false;
_this._fogEnabled = true;
_this._fogMode = Scene2.FOGMODE_NONE;
_this.fogColor = new BABYLON2.Color3(0.2, 0.2, 0.3);
_this.fogDensity = 0.1;
_this.fogStart = 0;
_this.fogEnd = 1e3;
_this._shadowsEnabled = true;
_this._lightsEnabled = true;
_this.activeCameras = new Array();
_this._texturesEnabled = true;
_this.particlesEnabled = true;
_this.spritesEnabled = true;
_this._skeletonsEnabled = true;
_this.lensFlaresEnabled = true;
_this.collisionsEnabled = true;
_this.gravity = new BABYLON2.Vector3(0, -9.807, 0);
_this.postProcessesEnabled = true;
_this.postProcesses = new Array();
_this.renderTargetsEnabled = true;
_this.dumpNextRenderTargets = false;
_this.customRenderTargets = new Array();
_this.importedMeshesFiles = new Array();
_this.probesEnabled = true;
_this._meshesForIntersections = new BABYLON2.SmartArrayNoDuplicate(256);
_this.proceduralTexturesEnabled = true;
_this._totalVertices = new BABYLON2.PerfCounter();
_this._activeIndices = new BABYLON2.PerfCounter();
_this._activeParticles = new BABYLON2.PerfCounter();
_this._activeBones = new BABYLON2.PerfCounter();
_this._animationTime = 0;
_this.animationTimeScale = 1;
_this._renderId = 0;
_this._frameId = 0;
_this._executeWhenReadyTimeoutId = -1;
_this._intermediateRendering = false;
_this._viewUpdateFlag = -1;
_this._projectionUpdateFlag = -1;
_this._alternateViewUpdateFlag = -1;
_this._alternateProjectionUpdateFlag = -1;
_this._toBeDisposed = new Array(256);
_this._activeRequests = new Array();
_this._pendingData = new Array();
_this._isDisposed = false;
_this.dispatchAllSubMeshesOfActiveMeshes = false;
_this._activeMeshes = new BABYLON2.SmartArray(256);
_this._processedMaterials = new BABYLON2.SmartArray(256);
_this._renderTargets = new BABYLON2.SmartArrayNoDuplicate(256);
_this._activeParticleSystems = new BABYLON2.SmartArray(256);
_this._activeSkeletons = new BABYLON2.SmartArrayNoDuplicate(32);
_this._softwareSkinnedMeshes = new BABYLON2.SmartArrayNoDuplicate(32);
_this._activeAnimatables = new Array();
_this._transformMatrix = BABYLON2.Matrix.Zero();
_this._useAlternateCameraConfiguration = false;
_this._alternateRendering = false;
_this.requireLightSorting = false;
_this._components = [];
_this._serializableComponents = [];
_this._transientComponents = [];
_this._beforeCameraUpdateStage = BABYLON2.Stage.Create();
_this._beforeClearStage = BABYLON2.Stage.Create();
_this._gatherRenderTargetsStage = BABYLON2.Stage.Create();
_this._gatherActiveCameraRenderTargetsStage = BABYLON2.Stage.Create();
_this._isReadyForMeshStage = BABYLON2.Stage.Create();
_this._beforeEvaluateActiveMeshStage = BABYLON2.Stage.Create();
_this._evaluateSubMeshStage = BABYLON2.Stage.Create();
_this._activeMeshStage = BABYLON2.Stage.Create();
_this._cameraDrawRenderTargetStage = BABYLON2.Stage.Create();
_this._beforeCameraDrawStage = BABYLON2.Stage.Create();
_this._beforeRenderingGroupDrawStage = BABYLON2.Stage.Create();
_this._beforeRenderingMeshStage = BABYLON2.Stage.Create();
_this._afterRenderingMeshStage = BABYLON2.Stage.Create();
_this._afterRenderingGroupDrawStage = BABYLON2.Stage.Create();
_this._afterCameraDrawStage = BABYLON2.Stage.Create();
_this._afterRenderStage = BABYLON2.Stage.Create();
_this._pointerMoveStage = BABYLON2.Stage.Create();
_this._pointerDownStage = BABYLON2.Stage.Create();
_this._pointerUpStage = BABYLON2.Stage.Create();
_this._defaultMeshCandidates = {
data: [],
length: 0
};
_this._defaultSubMeshCandidates = {
data: [],
length: 0
};
_this._activeMeshesFrozen = false;
_this._allowPostProcessClearColor = true;
_this.getDeterministicFrameTime = function() {
return 1e3 / 60;
};
_this._tempPickingRay = BABYLON2.Ray ? BABYLON2.Ray.Zero() : null;
_this._blockMaterialDirtyMechanism = false;
_this._engine = engine || BABYLON2.Engine.LastCreatedEngine;
_this._engine.scenes.push(_this);
_this._uid = null;
_this._renderingManager = new BABYLON2.RenderingManager(_this);
if (BABYLON2.PostProcessManager) {
_this.postProcessManager = new BABYLON2.PostProcessManager(_this);
}
if (BABYLON2.Tools.IsWindowObjectExist()) {
}
_this.workerCollisions = false;
_this._createUbo();
if (BABYLON2.ImageProcessingConfiguration) {
_this._imageProcessingConfiguration = new BABYLON2.ImageProcessingConfiguration();
}
_this.setDefaultCandidateProviders();
return _this;
}
Object.defineProperty(Scene2.prototype, "environmentTexture", {
/**
* Texture used in all pbr material as the reflection texture.
* As in the majority of the scene they are the same (exception for multi room and so on),
* this is easier to reference from here than from all the materials.
*/
get: function() {
return this._environmentTexture;
},
/**
* Texture used in all pbr material as the reflection texture.
* As in the majority of the scene they are the same (exception for multi room and so on),
* this is easier to set here than in all the materials.
*/
set: function(value) {
if (this._environmentTexture === value) {
return;
}
this._environmentTexture = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "imageProcessingConfiguration", {
/**
* Default image processing configuration used either in the rendering
* Forward main pass or through the imageProcessingPostProcess if present.
* As in the majority of the scene they are the same (exception for multi camera),
* this is easier to reference from here than from all the materials and post process.
*
* No setter as we it is a shared configuration, you can set the values instead.
*/
get: function() {
return this._imageProcessingConfiguration;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "forceWireframe", {
get: function() {
return this._forceWireframe;
},
/**
* Gets or sets a boolean indicating if all rendering must be done in wireframe
*/
set: function(value) {
if (this._forceWireframe === value) {
return;
}
this._forceWireframe = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "forcePointsCloud", {
get: function() {
return this._forcePointsCloud;
},
/**
* Gets or sets a boolean indicating if all rendering must be done in point cloud
*/
set: function(value) {
if (this._forcePointsCloud === value) {
return;
}
this._forcePointsCloud = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "animationPropertiesOverride", {
/**
* Gets or sets the animation properties override
*/
get: function() {
return this._animationPropertiesOverride;
},
set: function(value) {
this._animationPropertiesOverride = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "onDispose", {
/** Sets a function to be executed when this scene is disposed. */
set: function(callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "beforeRender", {
/** Sets a function to be executed before rendering this scene */
set: function(callback) {
if (this._onBeforeRenderObserver) {
this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
}
if (callback) {
this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "afterRender", {
/** Sets a function to be executed after rendering this scene */
set: function(callback) {
if (this._onAfterRenderObserver) {
this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
}
if (callback) {
this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "beforeCameraRender", {
/** Sets a function to be executed before rendering a camera*/
set: function(callback) {
if (this._onBeforeCameraRenderObserver) {
this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
}
this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "afterCameraRender", {
/** Sets a function to be executed after rendering a camera*/
set: function(callback) {
if (this._onAfterCameraRenderObserver) {
this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
}
this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "unTranslatedPointer", {
/**
* Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
*/
get: function() {
return new BABYLON2.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "useRightHandedSystem", {
get: function() {
return this._useRightHandedSystem;
},
/**
* Gets or sets a boolean indicating if the scene must use right-handed coordinates system
*/
set: function(value) {
if (this._useRightHandedSystem === value) {
return;
}
this._useRightHandedSystem = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Scene2.prototype.setStepId = function(newStepId) {
this._currentStepId = newStepId;
};
Scene2.prototype.getStepId = function() {
return this._currentStepId;
};
Scene2.prototype.getInternalStep = function() {
return this._currentInternalStep;
};
Object.defineProperty(Scene2.prototype, "fogEnabled", {
get: function() {
return this._fogEnabled;
},
/**
* Gets or sets a boolean indicating if fog is enabled on this scene
* @see http://doc.babylonjs.com/babylon101/environment#fog
* (Default is true)
*/
set: function(value) {
if (this._fogEnabled === value) {
return;
}
this._fogEnabled = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "fogMode", {
get: function() {
return this._fogMode;
},
/**
* Gets or sets the fog mode to use
* @see http://doc.babylonjs.com/babylon101/environment#fog
* | mode | value |
* | --- | --- |
* | FOGMODE_NONE | 0 |
* | FOGMODE_EXP | 1 |
* | FOGMODE_EXP2 | 2 |
* | FOGMODE_LINEAR | 3 |
*/
set: function(value) {
if (this._fogMode === value) {
return;
}
this._fogMode = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "shadowsEnabled", {
get: function() {
return this._shadowsEnabled;
},
/**
* Gets or sets a boolean indicating if shadows are enabled on this scene
*/
set: function(value) {
if (this._shadowsEnabled === value) {
return;
}
this._shadowsEnabled = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.LightDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "lightsEnabled", {
get: function() {
return this._lightsEnabled;
},
/**
* Gets or sets a boolean indicating if lights are enabled on this scene
*/
set: function(value) {
if (this._lightsEnabled === value) {
return;
}
this._lightsEnabled = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.LightDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "defaultMaterial", {
/** The default material used on meshes when no material is affected */
get: function() {
if (!this._defaultMaterial) {
this._defaultMaterial = new BABYLON2.StandardMaterial("default material", this);
}
return this._defaultMaterial;
},
/** The default material used on meshes when no material is affected */
set: function(value) {
this._defaultMaterial = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "texturesEnabled", {
get: function() {
return this._texturesEnabled;
},
/**
* Gets or sets a boolean indicating if textures are enabled on this scene
*/
set: function(value) {
if (this._texturesEnabled === value) {
return;
}
this._texturesEnabled = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "skeletonsEnabled", {
get: function() {
return this._skeletonsEnabled;
},
/**
* Gets or sets a boolean indicating if skeletons are enabled on this scene
*/
set: function(value) {
if (this._skeletonsEnabled === value) {
return;
}
this._skeletonsEnabled = value;
this.markAllMaterialsAsDirty(BABYLON2.Material.AttributesDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "_isAlternateRenderingEnabled", {
/** @hidden */
get: function() {
return this._alternateRendering;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "frustumPlanes", {
/**
* Gets the list of frustum planes (built from the active camera)
*/
get: function() {
return this._frustumPlanes;
},
enumerable: true,
configurable: true
});
Scene2.prototype._registerTransientComponents = function() {
if (this._transientComponents.length > 0) {
for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
var component = _a[_i];
component.register();
}
this._transientComponents = [];
}
};
Scene2.prototype._addComponent = function(component) {
this._components.push(component);
this._transientComponents.push(component);
var serializableComponent = component;
if (serializableComponent.addFromContainer) {
this._serializableComponents.push(serializableComponent);
}
};
Scene2.prototype._getComponent = function(name) {
for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
var component = _a[_i];
if (component.name === name) {
return component;
}
}
return null;
};
Scene2.prototype._getDefaultMeshCandidates = function() {
this._defaultMeshCandidates.data = this.meshes;
this._defaultMeshCandidates.length = this.meshes.length;
return this._defaultMeshCandidates;
};
Scene2.prototype._getDefaultSubMeshCandidates = function(mesh2) {
this._defaultSubMeshCandidates.data = mesh2.subMeshes;
this._defaultSubMeshCandidates.length = mesh2.subMeshes.length;
return this._defaultSubMeshCandidates;
};
Scene2.prototype.setDefaultCandidateProviders = function() {
this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
};
Object.defineProperty(Scene2.prototype, "workerCollisions", {
/**
* Gets a boolean indicating if collisions are processed on a web worker
* @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
*/
get: function() {
return this._workerCollisions;
},
set: function(enabled) {
if (!BABYLON2.CollisionCoordinatorLegacy) {
return;
}
enabled = enabled && !!Worker && !!BABYLON2.CollisionWorker;
this._workerCollisions = enabled;
if (this.collisionCoordinator) {
this.collisionCoordinator.destroy();
}
this.collisionCoordinator = enabled ? new BABYLON2.CollisionCoordinatorWorker() : new BABYLON2.CollisionCoordinatorLegacy();
this.collisionCoordinator.init(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "meshUnderPointer", {
/**
* Gets the mesh that is currently under the pointer
*/
get: function() {
return this._pointerOverMesh;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "pointerX", {
/**
* Gets the current on-screen X position of the pointer
*/
get: function() {
return this._pointerX;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Scene2.prototype, "pointerY", {
/**
* Gets the current on-screen Y position of the pointer
*/
get: function() {
return this._pointerY;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getCachedMaterial = function() {
return this._cachedMaterial;
};
Scene2.prototype.getCachedEffect = function() {
return this._cachedEffect;
};
Scene2.prototype.getCachedVisibility = function() {
return this._cachedVisibility;
};
Scene2.prototype.isCachedMaterialInvalid = function(material, effect, visibility) {
if (visibility === void 0) {
visibility = 1;
}
return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
};
Scene2.prototype.getEngine = function() {
return this._engine;
};
Scene2.prototype.getTotalVertices = function() {
return this._totalVertices.current;
};
Object.defineProperty(Scene2.prototype, "totalVerticesPerfCounter", {
/**
* Gets the performance counter for total vertices
* @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
*/
get: function() {
return this._totalVertices;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getActiveIndices = function() {
return this._activeIndices.current;
};
Object.defineProperty(Scene2.prototype, "totalActiveIndicesPerfCounter", {
/**
* Gets the performance counter for active indices
* @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
*/
get: function() {
return this._activeIndices;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getActiveParticles = function() {
return this._activeParticles.current;
};
Object.defineProperty(Scene2.prototype, "activeParticlesPerfCounter", {
/**
* Gets the performance counter for active particles
* @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
*/
get: function() {
return this._activeParticles;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getActiveBones = function() {
return this._activeBones.current;
};
Object.defineProperty(Scene2.prototype, "activeBonesPerfCounter", {
/**
* Gets the performance counter for active bones
* @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
*/
get: function() {
return this._activeBones;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getInterFramePerfCounter = function() {
BABYLON2.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene2.prototype, "interFramePerfCounter", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getLastFrameDuration = function() {
BABYLON2.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene2.prototype, "lastFramePerfCounter", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getEvaluateActiveMeshesDuration = function() {
BABYLON2.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene2.prototype, "evaluateActiveMeshesDurationPerfCounter", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getActiveMeshes = function() {
return this._activeMeshes;
};
Scene2.prototype.getRenderTargetsDuration = function() {
BABYLON2.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Scene2.prototype.getRenderDuration = function() {
BABYLON2.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene2.prototype, "renderDurationPerfCounter", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getParticlesDuration = function() {
BABYLON2.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene2.prototype, "particlesDurationPerfCounter", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getSpritesDuration = function() {
BABYLON2.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
return 0;
};
Object.defineProperty(Scene2.prototype, "spriteDuractionPerfCounter", {
/** @hidden */
get: function() {
BABYLON2.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
return null;
},
enumerable: true,
configurable: true
});
Scene2.prototype.getAnimationRatio = function() {
return this._animationRatio !== void 0 ? this._animationRatio : 1;
};
Scene2.prototype.getRenderId = function() {
return this._renderId;
};
Scene2.prototype.getFrameId = function() {
return this._frameId;
};
Scene2.prototype.incrementRenderId = function() {
this._renderId++;
};
Scene2.prototype._updatePointerPosition = function(evt) {
var canvasRect = this._engine.getRenderingCanvasClientRect();
if (!canvasRect) {
return;
}
this._pointerX = evt.clientX - canvasRect.left;
this._pointerY = evt.clientY - canvasRect.top;
this._unTranslatedPointerX = this._pointerX;
this._unTranslatedPointerY = this._pointerY;
};
Scene2.prototype._createUbo = function() {
this._sceneUbo = new BABYLON2.UniformBuffer(this._engine, void 0, true);
this._sceneUbo.addUniform("viewProjection", 16);
this._sceneUbo.addUniform("view", 16);
};
Scene2.prototype._createAlternateUbo = function() {
this._alternateSceneUbo = new BABYLON2.UniformBuffer(this._engine, void 0, true);
this._alternateSceneUbo.addUniform("viewProjection", 16);
this._alternateSceneUbo.addUniform("view", 16);
};
Scene2.prototype._setRayOnPointerInfo = function(pointerInfo) {
if (pointerInfo.pickInfo) {
if (!pointerInfo.pickInfo.ray) {
pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON2.Matrix.Identity(), this.activeCamera);
}
}
};
Scene2.prototype.simulatePointerMove = function(pickResult, pointerEventInit) {
var evt = new PointerEvent("pointermove", pointerEventInit);
if (this._checkPrePointerObservable(pickResult, evt, BABYLON2.PointerEventTypes.POINTERMOVE)) {
return this;
}
return this._processPointerMove(pickResult, evt);
};
Scene2.prototype._processPointerMove = function(pickResult, evt) {
var canvas2 = this._engine.getRenderingCanvas();
if (!canvas2) {
return this;
}
canvas2.style.cursor = this.defaultCursor;
var isMeshPicked = pickResult && pickResult.hit && pickResult.pickedMesh ? true : false;
if (isMeshPicked) {
this.setPointerOverMesh(pickResult.pickedMesh);
if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
if (this._pointerOverMesh.actionManager.hoverCursor) {
canvas2.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
} else {
canvas2.style.cursor = this.hoverCursor;
}
}
} else {
this.setPointerOverMesh(null);
}
for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
var step = _a[_i];
pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas2);
}
if (pickResult) {
var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON2.PointerEventTypes.POINTERWHEEL : BABYLON2.PointerEventTypes.POINTERMOVE;
if (this.onPointerMove) {
this.onPointerMove(evt, pickResult, type);
}
if (this.onPointerObservable.hasObservers()) {
var pi = new BABYLON2.PointerInfo(type, evt, pickResult);
this._setRayOnPointerInfo(pi);
this.onPointerObservable.notifyObservers(pi, type);
}
}
return this;
};
Scene2.prototype._checkPrePointerObservable = function(pickResult, evt, type) {
var pi = new BABYLON2.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
if (pickResult) {
pi.ray = pickResult.ray;
}
this.onPrePointerObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return true;
} else {
return false;
}
};
Scene2.prototype.simulatePointerDown = function(pickResult, pointerEventInit) {
var evt = new PointerEvent("pointerdown", pointerEventInit);
if (this._checkPrePointerObservable(pickResult, evt, BABYLON2.PointerEventTypes.POINTERDOWN)) {
return this;
}
return this._processPointerDown(pickResult, evt);
};
Scene2.prototype._processPointerDown = function(pickResult, evt) {
var _this = this;
if (pickResult && pickResult.hit && pickResult.pickedMesh) {
this._pickedDownMesh = pickResult.pickedMesh;
var actionManager = pickResult.pickedMesh.actionManager;
if (actionManager) {
if (actionManager.hasPickTriggers) {
actionManager.processTrigger(BABYLON2.ActionManager.OnPickDownTrigger, BABYLON2.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
switch (evt.button) {
case 0:
actionManager.processTrigger(BABYLON2.ActionManager.OnLeftPickTrigger, BABYLON2.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
break;
case 1:
actionManager.processTrigger(BABYLON2.ActionManager.OnCenterPickTrigger, BABYLON2.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
break;
case 2:
actionManager.processTrigger(BABYLON2.ActionManager.OnRightPickTrigger, BABYLON2.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
break;
}
}
if (actionManager.hasSpecificTrigger(BABYLON2.ActionManager.OnLongPressTrigger)) {
window.setTimeout(function() {
var pickResult2 = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function(mesh2) {
return mesh2.isPickable && mesh2.isVisible && mesh2.isReady() && mesh2.actionManager && mesh2.actionManager.hasSpecificTrigger(BABYLON2.ActionManager.OnLongPressTrigger) && mesh2 == _this._pickedDownMesh;
}, false, _this.cameraToUseForPointers);
if (pickResult2 && pickResult2.hit && pickResult2.pickedMesh && actionManager) {
if (_this._totalPointersPressed !== 0 && Date.now() - _this._startingPointerTime > Scene2.LongPressDelay && !_this._isPointerSwiping()) {
_this._startingPointerTime = 0;
actionManager.processTrigger(BABYLON2.ActionManager.OnLongPressTrigger, BABYLON2.ActionEvent.CreateNew(pickResult2.pickedMesh, evt));
}
}
}, Scene2.LongPressDelay);
}
}
} else {
for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
var step = _a[_i];
pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
}
}
if (pickResult) {
var type = BABYLON2.PointerEventTypes.POINTERDOWN;
if (this.onPointerDown) {
this.onPointerDown(evt, pickResult, type);
}
if (this.onPointerObservable.hasObservers()) {
var pi = new BABYLON2.PointerInfo(type, evt, pickResult);
this._setRayOnPointerInfo(pi);
this.onPointerObservable.notifyObservers(pi, type);
}
}
return this;
};
Scene2.prototype.simulatePointerUp = function(pickResult, pointerEventInit) {
var evt = new PointerEvent("pointerup", pointerEventInit);
var clickInfo = new ClickInfo();
clickInfo.singleClick = true;
clickInfo.ignore = true;
if (this._checkPrePointerObservable(pickResult, evt, BABYLON2.PointerEventTypes.POINTERUP)) {
return this;
}
return this._processPointerUp(pickResult, evt, clickInfo);
};
Scene2.prototype._processPointerUp = function(pickResult, evt, clickInfo) {
if (pickResult && pickResult && pickResult.pickedMesh) {
this._pickedUpMesh = pickResult.pickedMesh;
if (this._pickedDownMesh === this._pickedUpMesh) {
if (this.onPointerPick) {
this.onPointerPick(evt, pickResult);
}
if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
var type_1 = BABYLON2.PointerEventTypes.POINTERPICK;
var pi = new BABYLON2.PointerInfo(type_1, evt, pickResult);
this._setRayOnPointerInfo(pi);
this.onPointerObservable.notifyObservers(pi, type_1);
}
}
if (pickResult.pickedMesh.actionManager) {
if (clickInfo.ignore) {
pickResult.pickedMesh.actionManager.processTrigger(BABYLON2.ActionManager.OnPickUpTrigger, BABYLON2.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
}
if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
pickResult.pickedMesh.actionManager.processTrigger(BABYLON2.ActionManager.OnPickTrigger, BABYLON2.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
}
if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON2.ActionManager.OnDoublePickTrigger)) {
pickResult.pickedMesh.actionManager.processTrigger(BABYLON2.ActionManager.OnDoublePickTrigger, BABYLON2.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
}
}
} else {
if (!clickInfo.ignore) {
for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
var step = _a[_i];
pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
}
}
}
if (this._pickedDownMesh && this._pickedDownMesh.actionManager && this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON2.ActionManager.OnPickOutTrigger) && this._pickedDownMesh !== this._pickedUpMesh) {
this._pickedDownMesh.actionManager.processTrigger(BABYLON2.ActionManager.OnPickOutTrigger, BABYLON2.ActionEvent.CreateNew(this._pickedDownMesh, evt));
}
var type = BABYLON2.PointerEventTypes.POINTERUP;
if (this.onPointerObservable.hasObservers()) {
if (!clickInfo.ignore) {
if (!clickInfo.hasSwiped) {
if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERTAP)) {
var type_2 = BABYLON2.PointerEventTypes.POINTERTAP;
var pi = new BABYLON2.PointerInfo(type_2, evt, pickResult);
this._setRayOnPointerInfo(pi);
this.onPointerObservable.notifyObservers(pi, type_2);
}
if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP)) {
var type_3 = BABYLON2.PointerEventTypes.POINTERDOUBLETAP;
var pi = new BABYLON2.PointerInfo(type_3, evt, pickResult);
this._setRayOnPointerInfo(pi);
this.onPointerObservable.notifyObservers(pi, type_3);
}
}
} else {
var pi = new BABYLON2.PointerInfo(type, evt, pickResult);
this._setRayOnPointerInfo(pi);
this.onPointerObservable.notifyObservers(pi, type);
}
}
if (this.onPointerUp) {
this.onPointerUp(evt, pickResult, type);
}
return this;
};
Scene2.prototype.isPointerCaptured = function(pointerId) {
if (pointerId === void 0) {
pointerId = 0;
}
return this._pointerCaptures[pointerId];
};
Scene2.prototype._isPointerSwiping = function() {
return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene2.DragMovementThreshold || Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene2.DragMovementThreshold;
};
Scene2.prototype.attachControl = function(attachUp, attachDown, attachMove) {
var _this = this;
if (attachUp === void 0) {
attachUp = true;
}
if (attachDown === void 0) {
attachDown = true;
}
if (attachMove === void 0) {
attachMove = true;
}
this._initActionManager = function(act, clickInfo) {
if (!_this._meshPickProceed) {
var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
_this._currentPickResult = pickResult;
if (pickResult) {
act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh.actionManager : null;
}
_this._meshPickProceed = true;
}
return act;
};
this._delayedSimpleClick = function(btn, clickInfo, cb) {
if (Date.now() - _this._previousStartingPointerTime > Scene2.DoubleClickDelay && !_this._doubleClickOccured || btn !== _this._previousButtonPressed) {
_this._doubleClickOccured = false;
clickInfo.singleClick = true;
clickInfo.ignore = false;
cb(clickInfo, _this._currentPickResult);
}
};
this._initClickEvent = function(obs1, obs2, evt, cb) {
var clickInfo = new ClickInfo();
_this._currentPickResult = null;
var act = null;
var checkPicking = obs1.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERPICK) || obs1.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERTAP) || obs1.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP);
if (!checkPicking && BABYLON2.ActionManager && BABYLON2.ActionManager.HasPickTriggers) {
act = _this._initActionManager(act, clickInfo);
if (act) {
checkPicking = act.hasPickTriggers;
}
}
if (checkPicking) {
var btn = evt.button;
clickInfo.hasSwiped = _this._isPointerSwiping();
if (!clickInfo.hasSwiped) {
var checkSingleClickImmediately = !Scene2.ExclusiveDoubleClickMode;
if (!checkSingleClickImmediately) {
checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP);
if (checkSingleClickImmediately && !BABYLON2.ActionManager.HasSpecificTrigger(BABYLON2.ActionManager.OnDoublePickTrigger)) {
act = _this._initActionManager(act, clickInfo);
if (act) {
checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON2.ActionManager.OnDoublePickTrigger);
}
}
}
if (checkSingleClickImmediately) {
if (Date.now() - _this._previousStartingPointerTime > Scene2.DoubleClickDelay || btn !== _this._previousButtonPressed) {
clickInfo.singleClick = true;
cb(clickInfo, _this._currentPickResult);
}
} else {
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
_this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene2.DoubleClickDelay);
}
var checkDoubleClick = obs1.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP);
if (!checkDoubleClick && BABYLON2.ActionManager.HasSpecificTrigger(BABYLON2.ActionManager.OnDoublePickTrigger)) {
act = _this._initActionManager(act, clickInfo);
if (act) {
checkDoubleClick = act.hasSpecificTrigger(BABYLON2.ActionManager.OnDoublePickTrigger);
}
}
if (checkDoubleClick) {
if (btn === _this._previousButtonPressed && Date.now() - _this._previousStartingPointerTime < Scene2.DoubleClickDelay && !_this._doubleClickOccured) {
if (!clickInfo.hasSwiped && !_this._isPointerSwiping()) {
_this._previousStartingPointerTime = 0;
_this._doubleClickOccured = true;
clickInfo.doubleClick = true;
clickInfo.ignore = false;
if (Scene2.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
clearTimeout(_this._previousDelayedSimpleClickTimeout);
}
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
cb(clickInfo, _this._currentPickResult);
} else {
_this._doubleClickOccured = false;
_this._previousStartingPointerTime = _this._startingPointerTime;
_this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
_this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
_this._previousButtonPressed = btn;
if (Scene2.ExclusiveDoubleClickMode) {
if (_this._previousDelayedSimpleClickTimeout) {
clearTimeout(_this._previousDelayedSimpleClickTimeout);
}
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
cb(clickInfo, _this._previousPickResult);
} else {
cb(clickInfo, _this._currentPickResult);
}
}
} else {
_this._doubleClickOccured = false;
_this._previousStartingPointerTime = _this._startingPointerTime;
_this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
_this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
_this._previousButtonPressed = btn;
}
}
}
}
clickInfo.ignore = true;
cb(clickInfo, _this._currentPickResult);
};
this._onPointerMove = function(evt) {
_this._updatePointerPosition(evt);
if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON2.PointerEventTypes.POINTERWHEEL : BABYLON2.PointerEventTypes.POINTERMOVE)) {
return;
}
if (!_this.cameraToUseForPointers && !_this.activeCamera) {
return;
}
if (!_this.pointerMovePredicate) {
_this.pointerMovePredicate = function(mesh2) {
return mesh2.isPickable && mesh2.isVisible && mesh2.isReady() && mesh2.isEnabled() && (mesh2.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || mesh2.actionManager !== null && mesh2.actionManager !== void 0);
};
}
var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
_this._processPointerMove(pickResult, evt);
};
this._onPointerDown = function(evt) {
_this._totalPointersPressed++;
_this._pickedDownMesh = null;
_this._meshPickProceed = false;
_this._updatePointerPosition(evt);
if (_this.preventDefaultOnPointerDown && canvas2) {
evt.preventDefault();
canvas2.focus();
}
if (_this._checkPrePointerObservable(null, evt, BABYLON2.PointerEventTypes.POINTERDOWN)) {
return;
}
if (!_this.cameraToUseForPointers && !_this.activeCamera) {
return;
}
_this._pointerCaptures[evt.pointerId] = true;
_this._startingPointerPosition.x = _this._pointerX;
_this._startingPointerPosition.y = _this._pointerY;
_this._startingPointerTime = Date.now();
if (!_this.pointerDownPredicate) {
_this.pointerDownPredicate = function(mesh2) {
return mesh2.isPickable && mesh2.isVisible && mesh2.isReady() && mesh2.isEnabled();
};
}
_this._pickedDownMesh = null;
var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
_this._processPointerDown(pickResult, evt);
};
this._onPointerUp = function(evt) {
if (_this._totalPointersPressed === 0) {
return;
}
_this._totalPointersPressed--;
_this._pickedUpMesh = null;
_this._meshPickProceed = false;
_this._updatePointerPosition(evt);
_this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function(clickInfo, pickResult) {
if (_this.onPrePointerObservable.hasObservers()) {
if (!clickInfo.ignore) {
if (!clickInfo.hasSwiped) {
if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERTAP)) {
if (_this._checkPrePointerObservable(null, evt, BABYLON2.PointerEventTypes.POINTERTAP)) {
return;
}
}
if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON2.PointerEventTypes.POINTERDOUBLETAP)) {
if (_this._checkPrePointerObservable(null, evt, BABYLON2.PointerEventTypes.POINTERDOUBLETAP)) {
return;
}
}
}
} else {
if (_this._checkPrePointerObservable(null, evt, BABYLON2.PointerEventTypes.POINTERUP)) {
return;
}
}
}
if (!_this.cameraToUseForPointers && !_this.activeCamera) {
return;
}
_this._pointerCaptures[evt.pointerId] = false;
if (!_this.pointerUpPredicate) {
_this.pointerUpPredicate = function(mesh2) {
return mesh2.isPickable && mesh2.isVisible && mesh2.isReady() && mesh2.isEnabled();
};
}
if (!_this._meshPickProceed && (BABYLON2.ActionManager && BABYLON2.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
_this._initActionManager(null, clickInfo);
}
if (!pickResult) {
pickResult = _this._currentPickResult;
}
_this._processPointerUp(pickResult, evt, clickInfo);
_this._previousPickResult = _this._currentPickResult;
});
};
this._onKeyDown = function(evt) {
var type = BABYLON2.KeyboardEventTypes.KEYDOWN;
if (_this.onPreKeyboardObservable.hasObservers()) {
var pi = new BABYLON2.KeyboardInfoPre(type, evt);
_this.onPreKeyboardObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (_this.onKeyboardObservable.hasObservers()) {
var pi = new BABYLON2.KeyboardInfo(type, evt);
_this.onKeyboardObservable.notifyObservers(pi, type);
}
if (_this.actionManager) {
_this.actionManager.processTrigger(BABYLON2.ActionManager.OnKeyDownTrigger, BABYLON2.ActionEvent.CreateNewFromScene(_this, evt));
}
};
this._onKeyUp = function(evt) {
var type = BABYLON2.KeyboardEventTypes.KEYUP;
if (_this.onPreKeyboardObservable.hasObservers()) {
var pi = new BABYLON2.KeyboardInfoPre(type, evt);
_this.onPreKeyboardObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (_this.onKeyboardObservable.hasObservers()) {
var pi = new BABYLON2.KeyboardInfo(type, evt);
_this.onKeyboardObservable.notifyObservers(pi, type);
}
if (_this.actionManager) {
_this.actionManager.processTrigger(BABYLON2.ActionManager.OnKeyUpTrigger, BABYLON2.ActionEvent.CreateNewFromScene(_this, evt));
}
};
var engine = this.getEngine();
this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function() {
if (!canvas2) {
return;
}
canvas2.addEventListener("keydown", _this._onKeyDown, false);
canvas2.addEventListener("keyup", _this._onKeyUp, false);
});
this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function() {
if (!canvas2) {
return;
}
canvas2.removeEventListener("keydown", _this._onKeyDown);
canvas2.removeEventListener("keyup", _this._onKeyUp);
});
var eventPrefix = BABYLON2.Tools.GetPointerPrefix();
var canvas2 = this._engine.getRenderingCanvas();
if (!canvas2) {
return;
}
if (attachMove) {
canvas2.addEventListener(eventPrefix + "move", this._onPointerMove, false);
canvas2.addEventListener("mousewheel", this._onPointerMove, false);
canvas2.addEventListener("DOMMouseScroll", this._onPointerMove, false);
}
if (attachDown) {
canvas2.addEventListener(eventPrefix + "down", this._onPointerDown, false);
}
if (attachUp) {
window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
}
canvas2.tabIndex = 1;
};
Scene2.prototype.detachControl = function() {
var engine = this.getEngine();
var eventPrefix = BABYLON2.Tools.GetPointerPrefix();
var canvas2 = engine.getRenderingCanvas();
if (!canvas2) {
return;
}
canvas2.removeEventListener(eventPrefix + "move", this._onPointerMove);
canvas2.removeEventListener(eventPrefix + "down", this._onPointerDown);
window.removeEventListener(eventPrefix + "up", this._onPointerUp);
if (this._onCanvasBlurObserver) {
engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
}
if (this._onCanvasFocusObserver) {
engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
}
canvas2.removeEventListener("mousewheel", this._onPointerMove);
canvas2.removeEventListener("DOMMouseScroll", this._onPointerMove);
canvas2.removeEventListener("keydown", this._onKeyDown);
canvas2.removeEventListener("keyup", this._onKeyUp);
this.onKeyboardObservable.clear();
this.onPreKeyboardObservable.clear();
this.onPointerObservable.clear();
this.onPrePointerObservable.clear();
};
Scene2.prototype.isReady = function() {
if (this._isDisposed) {
return false;
}
if (this._pendingData.length > 0) {
return false;
}
var index;
var engine = this.getEngine();
for (index = 0; index < this.geometries.length; index++) {
var geometry = this.geometries[index];
if (geometry.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_LOADING) {
return false;
}
}
for (index = 0; index < this.meshes.length; index++) {
var mesh2 = this.meshes[index];
if (!mesh2.isEnabled()) {
continue;
}
if (!mesh2.subMeshes || mesh2.subMeshes.length === 0) {
continue;
}
if (!mesh2.isReady(true)) {
return false;
}
var hardwareInstancedRendering = mesh2.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh2.instances.length > 0;
for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
var step = _a[_i];
if (!step.action(mesh2, hardwareInstancedRendering)) {
return false;
}
}
}
if (this.activeCameras && this.activeCameras.length > 0) {
for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
var camera2 = _c[_b];
if (!camera2.isReady(true)) {
return false;
}
}
} else if (this.activeCamera) {
if (!this.activeCamera.isReady(true)) {
return false;
}
}
for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
var particleSystem = _e[_d];
if (!particleSystem.isReady()) {
return false;
}
}
return true;
};
Scene2.prototype.resetCachedMaterial = function() {
this._cachedMaterial = null;
this._cachedEffect = null;
this._cachedVisibility = null;
};
Scene2.prototype.registerBeforeRender = function(func) {
this.onBeforeRenderObservable.add(func);
};
Scene2.prototype.unregisterBeforeRender = function(func) {
this.onBeforeRenderObservable.removeCallback(func);
};
Scene2.prototype.registerAfterRender = function(func) {
this.onAfterRenderObservable.add(func);
};
Scene2.prototype.unregisterAfterRender = function(func) {
this.onAfterRenderObservable.removeCallback(func);
};
Scene2.prototype._executeOnceBeforeRender = function(func) {
var _this = this;
var execFunc = function() {
func();
setTimeout(function() {
_this.unregisterBeforeRender(execFunc);
});
};
this.registerBeforeRender(execFunc);
};
Scene2.prototype.executeOnceBeforeRender = function(func, timeout2) {
var _this = this;
if (timeout2 !== void 0) {
setTimeout(function() {
_this._executeOnceBeforeRender(func);
}, timeout2);
} else {
this._executeOnceBeforeRender(func);
}
};
Scene2.prototype._addPendingData = function(data2) {
this._pendingData.push(data2);
};
Scene2.prototype._removePendingData = function(data2) {
var wasLoading = this.isLoading;
var index = this._pendingData.indexOf(data2);
if (index !== -1) {
this._pendingData.splice(index, 1);
}
if (wasLoading && !this.isLoading) {
this.onDataLoadedObservable.notifyObservers(this);
}
};
Scene2.prototype.getWaitingItemsCount = function() {
return this._pendingData.length;
};
Object.defineProperty(Scene2.prototype, "isLoading", {
/**
* Returns a boolean indicating if the scene is still loading data
*/
get: function() {
return this._pendingData.length > 0;
},
enumerable: true,
configurable: true
});
Scene2.prototype.executeWhenReady = function(func) {
var _this = this;
this.onReadyObservable.add(func);
if (this._executeWhenReadyTimeoutId !== -1) {
return;
}
this._executeWhenReadyTimeoutId = setTimeout(function() {
_this._checkIsReady();
}, 150);
};
Scene2.prototype.whenReadyAsync = function() {
var _this = this;
return new Promise(function(resolve) {
_this.executeWhenReady(function() {
resolve();
});
});
};
Scene2.prototype._checkIsReady = function() {
var _this = this;
this._registerTransientComponents();
if (this.isReady()) {
this.onReadyObservable.notifyObservers(this);
this.onReadyObservable.clear();
this._executeWhenReadyTimeoutId = -1;
return;
}
this._executeWhenReadyTimeoutId = setTimeout(function() {
_this._checkIsReady();
}, 150);
};
Scene2.prototype.beginWeightedAnimation = function(target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
if (weight === void 0) {
weight = 1;
}
if (speedRatio === void 0) {
speedRatio = 1;
}
var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
returnedAnimatable.weight = weight;
return returnedAnimatable;
};
Scene2.prototype.beginAnimation = function(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
if (speedRatio === void 0) {
speedRatio = 1;
}
if (stopCurrent === void 0) {
stopCurrent = true;
}
if (from > to && speedRatio > 0) {
speedRatio *= -1;
}
if (stopCurrent) {
this.stopAnimation(target, void 0, targetMask);
}
if (!animatable) {
animatable = new BABYLON2.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
}
var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
if (target.animations && shouldRunTargetAnimations) {
animatable.appendAnimations(target, target.animations);
}
if (target.getAnimatables) {
var animatables = target.getAnimatables();
for (var index = 0; index < animatables.length; index++) {
this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
}
}
animatable.reset();
return animatable;
};
Scene2.prototype.beginDirectAnimation = function(target, animations, from, to, loop, speedRatio, onAnimationEnd) {
if (speedRatio === void 0) {
speedRatio = 1;
}
var animatable = new BABYLON2.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
return animatable;
};
Scene2.prototype.beginDirectHierarchyAnimation = function(target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
var children = target.getDescendants(directDescendantsOnly);
var result = [];
result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
var child = children_1[_i];
result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
}
return result;
};
Scene2.prototype.getAnimatableByTarget = function(target) {
for (var index = 0; index < this._activeAnimatables.length; index++) {
if (this._activeAnimatables[index].target === target) {
return this._activeAnimatables[index];
}
}
return null;
};
Scene2.prototype.getAllAnimatablesByTarget = function(target) {
var result = [];
for (var index = 0; index < this._activeAnimatables.length; index++) {
if (this._activeAnimatables[index].target === target) {
result.push(this._activeAnimatables[index]);
}
}
return result;
};
Object.defineProperty(Scene2.prototype, "animatables", {
/**
* Gets all animatable attached to the scene
*/
get: function() {
return this._activeAnimatables;
},
enumerable: true,
configurable: true
});
Scene2.prototype.stopAnimation = function(target, animationName, targetMask) {
var animatables = this.getAllAnimatablesByTarget(target);
for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
var animatable = animatables_1[_i];
animatable.stop(animationName, targetMask);
}
};
Scene2.prototype.stopAllAnimations = function() {
if (this._activeAnimatables) {
for (var i2 = 0; i2 < this._activeAnimatables.length; i2++) {
this._activeAnimatables[i2].stop();
}
this._activeAnimatables = [];
}
for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
var group = _a[_i];
group.stop();
}
};
Scene2.prototype._animate = function() {
if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
return;
}
var now2 = BABYLON2.Tools.Now;
if (!this._animationTimeLast) {
if (this._pendingData.length > 0) {
return;
}
this._animationTimeLast = now2;
}
var deltaTime = this.useConstantAnimationDeltaTime ? 16 : (now2 - this._animationTimeLast) * this.animationTimeScale;
this._animationTime += deltaTime;
this._animationTimeLast = now2;
for (var index = 0; index < this._activeAnimatables.length; index++) {
this._activeAnimatables[index]._animate(this._animationTime);
}
this._processLateAnimationBindings();
};
Scene2.prototype._registerTargetForLateAnimationBinding = function(runtimeAnimation, originalValue) {
var target = runtimeAnimation.target;
this._registeredForLateAnimationBindings.pushNoDuplicate(target);
if (!target._lateAnimationHolders) {
target._lateAnimationHolders = {};
}
if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
target._lateAnimationHolders[runtimeAnimation.targetPath] = {
totalWeight: 0,
animations: [],
originalValue
};
}
target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
};
Scene2.prototype._processLateAnimationBindingsForMatrices = function(holder) {
var normalizer = 1;
var finalPosition = BABYLON2.Tmp.Vector3[0];
var finalScaling = BABYLON2.Tmp.Vector3[1];
var finalQuaternion = BABYLON2.Tmp.Quaternion[0];
var startIndex = 0;
var originalAnimation = holder.animations[0];
var originalValue = holder.originalValue;
var scale = 1;
if (holder.totalWeight < 1) {
originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
scale = 1 - holder.totalWeight;
} else {
startIndex = 1;
normalizer = holder.totalWeight;
originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
scale = originalAnimation.weight / normalizer;
if (scale == 1) {
return originalAnimation.currentValue;
}
}
finalScaling.scaleInPlace(scale);
finalPosition.scaleInPlace(scale);
finalQuaternion.scaleInPlace(scale);
for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
var runtimeAnimation = holder.animations[animIndex];
var scale = runtimeAnimation.weight / normalizer;
var currentPosition = BABYLON2.Tmp.Vector3[2];
var currentScaling = BABYLON2.Tmp.Vector3[3];
var currentQuaternion = BABYLON2.Tmp.Quaternion[1];
runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
currentScaling.scaleAndAddToRef(scale, finalScaling);
currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
currentPosition.scaleAndAddToRef(scale, finalPosition);
}
BABYLON2.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
return originalAnimation._workValue;
};
Scene2.prototype._processLateAnimationBindingsForQuaternions = function(holder, refQuaternion) {
var originalAnimation = holder.animations[0];
var originalValue = holder.originalValue;
if (holder.animations.length === 1) {
BABYLON2.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1, holder.totalWeight), refQuaternion);
return refQuaternion;
}
var normalizer = 1;
var quaternions;
var weights;
if (holder.totalWeight < 1) {
var scale = 1 - holder.totalWeight;
quaternions = [];
weights = [];
quaternions.push(originalValue);
weights.push(scale);
} else {
if (holder.animations.length === 2) {
BABYLON2.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
return refQuaternion;
}
quaternions = [];
weights = [];
normalizer = holder.totalWeight;
}
for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
var runtimeAnimation = holder.animations[animIndex];
quaternions.push(runtimeAnimation.currentValue);
weights.push(runtimeAnimation.weight / normalizer);
}
var cumulativeAmount = 0;
var cumulativeQuaternion = null;
for (var index = 0; index < quaternions.length; ) {
if (!cumulativeQuaternion) {
BABYLON2.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
cumulativeQuaternion = refQuaternion;
cumulativeAmount = weights[index] + weights[index + 1];
index += 2;
continue;
}
cumulativeAmount += weights[index];
BABYLON2.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
index++;
}
return cumulativeQuaternion;
};
Scene2.prototype._processLateAnimationBindings = function() {
if (!this._registeredForLateAnimationBindings.length) {
return;
}
for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
var target = this._registeredForLateAnimationBindings.data[index];
for (var path in target._lateAnimationHolders) {
var holder = target._lateAnimationHolders[path];
var originalAnimation = holder.animations[0];
var originalValue = holder.originalValue;
var matrixDecomposeMode = BABYLON2.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m;
var finalValue = target[path];
if (matrixDecomposeMode) {
finalValue = this._processLateAnimationBindingsForMatrices(holder);
} else {
var quaternionMode = originalValue.w !== void 0;
if (quaternionMode) {
finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON2.Quaternion.Identity());
} else {
var startIndex = 0;
var normalizer = 1;
if (holder.totalWeight < 1) {
if (originalValue.scale) {
finalValue = originalValue.scale(1 - holder.totalWeight);
} else {
finalValue = originalValue * (1 - holder.totalWeight);
}
} else {
normalizer = holder.totalWeight;
var scale_1 = originalAnimation.weight / normalizer;
if (scale_1 !== 1) {
if (originalAnimation.currentValue.scale) {
finalValue = originalAnimation.currentValue.scale(scale_1);
} else {
finalValue = originalAnimation.currentValue * scale_1;
}
} else {
finalValue = originalAnimation.currentValue;
}
startIndex = 1;
}
for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
var runtimeAnimation = holder.animations[animIndex];
var scale = runtimeAnimation.weight / normalizer;
if (runtimeAnimation.currentValue.scaleAndAddToRef) {
runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
} else {
finalValue += runtimeAnimation.currentValue * scale;
}
}
}
}
target[path] = finalValue;
}
target._lateAnimationHolders = {};
}
this._registeredForLateAnimationBindings.reset();
};
Scene2.prototype._switchToAlternateCameraConfiguration = function(active) {
this._useAlternateCameraConfiguration = active;
};
Scene2.prototype.getViewMatrix = function() {
return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
};
Scene2.prototype.getProjectionMatrix = function() {
return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
};
Scene2.prototype.getTransformMatrix = function() {
return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
};
Scene2.prototype.setTransformMatrix = function(view, projection) {
if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
return;
}
this._viewUpdateFlag = view.updateFlag;
this._projectionUpdateFlag = projection.updateFlag;
this._viewMatrix = view;
this._projectionMatrix = projection;
this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
if (!this._frustumPlanes) {
this._frustumPlanes = BABYLON2.Frustum.GetPlanes(this._transformMatrix);
} else {
BABYLON2.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
}
if (this.activeCamera && this.activeCamera._alternateCamera) {
var otherCamera = this.activeCamera._alternateCamera;
otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON2.Tmp.Matrix[0]);
BABYLON2.Frustum.GetRightPlaneToRef(BABYLON2.Tmp.Matrix[0], this._frustumPlanes[3]);
}
if (this._sceneUbo.useUbo) {
this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
this._sceneUbo.updateMatrix("view", this._viewMatrix);
this._sceneUbo.update();
}
};
Scene2.prototype._setAlternateTransformMatrix = function(view, projection) {
if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
return;
}
this._alternateViewUpdateFlag = view.updateFlag;
this._alternateProjectionUpdateFlag = projection.updateFlag;
this._alternateViewMatrix = view;
this._alternateProjectionMatrix = projection;
if (!this._alternateTransformMatrix) {
this._alternateTransformMatrix = BABYLON2.Matrix.Zero();
}
this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
if (!this._alternateSceneUbo) {
this._createAlternateUbo();
}
if (this._alternateSceneUbo.useUbo) {
this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
this._alternateSceneUbo.update();
}
};
Scene2.prototype.getSceneUniformBuffer = function() {
return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
};
Scene2.prototype.getUniqueId = function() {
var result = Scene2._uniqueIdCounter;
Scene2._uniqueIdCounter++;
return result;
};
Scene2.prototype.addMesh = function(newMesh, recursive) {
var _this = this;
if (recursive === void 0) {
recursive = false;
}
this.meshes.push(newMesh);
if (this.collisionCoordinator) {
this.collisionCoordinator.onMeshAdded(newMesh);
}
newMesh._resyncLightSources();
this.onNewMeshAddedObservable.notifyObservers(newMesh);
if (recursive) {
newMesh.getChildMeshes().forEach(function(m) {
_this.addMesh(m);
});
}
};
Scene2.prototype.removeMesh = function(toRemove, recursive) {
var _this = this;
if (recursive === void 0) {
recursive = false;
}
var index = this.meshes.indexOf(toRemove);
if (index !== -1) {
this.meshes.splice(index, 1);
}
this.onMeshRemovedObservable.notifyObservers(toRemove);
if (recursive) {
toRemove.getChildMeshes().forEach(function(m) {
_this.removeMesh(m);
});
}
return index;
};
Scene2.prototype.addTransformNode = function(newTransformNode) {
this.transformNodes.push(newTransformNode);
this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
};
Scene2.prototype.removeTransformNode = function(toRemove) {
var index = this.transformNodes.indexOf(toRemove);
if (index !== -1) {
this.transformNodes.splice(index, 1);
}
this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene2.prototype.removeSkeleton = function(toRemove) {
var index = this.skeletons.indexOf(toRemove);
if (index !== -1) {
this.skeletons.splice(index, 1);
}
return index;
};
Scene2.prototype.removeMorphTargetManager = function(toRemove) {
var index = this.morphTargetManagers.indexOf(toRemove);
if (index !== -1) {
this.morphTargetManagers.splice(index, 1);
}
return index;
};
Scene2.prototype.removeLight = function(toRemove) {
var index = this.lights.indexOf(toRemove);
if (index !== -1) {
for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
mesh2._removeLightSource(toRemove);
}
this.lights.splice(index, 1);
this.sortLightsByPriority();
}
this.onLightRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene2.prototype.removeCamera = function(toRemove) {
var index = this.cameras.indexOf(toRemove);
if (index !== -1) {
this.cameras.splice(index, 1);
}
var index2 = this.activeCameras.indexOf(toRemove);
if (index2 !== -1) {
this.activeCameras.splice(index2, 1);
}
if (this.activeCamera === toRemove) {
if (this.cameras.length > 0) {
this.activeCamera = this.cameras[0];
} else {
this.activeCamera = null;
}
}
this.onCameraRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene2.prototype.removeParticleSystem = function(toRemove) {
var index = this.particleSystems.indexOf(toRemove);
if (index !== -1) {
this.particleSystems.splice(index, 1);
}
return index;
};
Scene2.prototype.removeAnimation = function(toRemove) {
var index = this.animations.indexOf(toRemove);
if (index !== -1) {
this.animations.splice(index, 1);
}
return index;
};
Scene2.prototype.removeAnimationGroup = function(toRemove) {
var index = this.animationGroups.indexOf(toRemove);
if (index !== -1) {
this.animationGroups.splice(index, 1);
}
return index;
};
Scene2.prototype.removeMultiMaterial = function(toRemove) {
var index = this.multiMaterials.indexOf(toRemove);
if (index !== -1) {
this.multiMaterials.splice(index, 1);
}
return index;
};
Scene2.prototype.removeMaterial = function(toRemove) {
var index = this.materials.indexOf(toRemove);
if (index !== -1) {
this.materials.splice(index, 1);
}
this.onMaterialRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene2.prototype.removeActionManager = function(toRemove) {
var index = this.actionManagers.indexOf(toRemove);
if (index !== -1) {
this.actionManagers.splice(index, 1);
}
return index;
};
Scene2.prototype.removeTexture = function(toRemove) {
var index = this.textures.indexOf(toRemove);
if (index !== -1) {
this.textures.splice(index, 1);
}
this.onTextureRemovedObservable.notifyObservers(toRemove);
return index;
};
Scene2.prototype.addLight = function(newLight) {
this.lights.push(newLight);
this.sortLightsByPriority();
for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
if (mesh2._lightSources.indexOf(newLight) === -1) {
mesh2._lightSources.push(newLight);
mesh2._resyncLightSources();
}
}
this.onNewLightAddedObservable.notifyObservers(newLight);
};
Scene2.prototype.sortLightsByPriority = function() {
if (this.requireLightSorting) {
this.lights.sort(BABYLON2.Light.CompareLightsPriority);
}
};
Scene2.prototype.addCamera = function(newCamera) {
this.cameras.push(newCamera);
this.onNewCameraAddedObservable.notifyObservers(newCamera);
};
Scene2.prototype.addSkeleton = function(newSkeleton) {
this.skeletons.push(newSkeleton);
};
Scene2.prototype.addParticleSystem = function(newParticleSystem) {
this.particleSystems.push(newParticleSystem);
};
Scene2.prototype.addAnimation = function(newAnimation) {
this.animations.push(newAnimation);
};
Scene2.prototype.addAnimationGroup = function(newAnimationGroup) {
this.animationGroups.push(newAnimationGroup);
};
Scene2.prototype.addMultiMaterial = function(newMultiMaterial) {
this.multiMaterials.push(newMultiMaterial);
};
Scene2.prototype.addMaterial = function(newMaterial) {
this.materials.push(newMaterial);
this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
};
Scene2.prototype.addMorphTargetManager = function(newMorphTargetManager) {
this.morphTargetManagers.push(newMorphTargetManager);
};
Scene2.prototype.addGeometry = function(newGeometry) {
this.geometries.push(newGeometry);
};
Scene2.prototype.addActionManager = function(newActionManager) {
this.actionManagers.push(newActionManager);
};
Scene2.prototype.addTexture = function(newTexture) {
this.textures.push(newTexture);
this.onNewTextureAddedObservable.notifyObservers(newTexture);
};
Scene2.prototype.switchActiveCamera = function(newCamera, attachControl) {
if (attachControl === void 0) {
attachControl = true;
}
var canvas2 = this._engine.getRenderingCanvas();
if (!canvas2) {
return;
}
if (this.activeCamera) {
this.activeCamera.detachControl(canvas2);
}
this.activeCamera = newCamera;
if (attachControl) {
newCamera.attachControl(canvas2);
}
};
Scene2.prototype.setActiveCameraByID = function(id) {
var camera2 = this.getCameraByID(id);
if (camera2) {
this.activeCamera = camera2;
return camera2;
}
return null;
};
Scene2.prototype.setActiveCameraByName = function(name) {
var camera2 = this.getCameraByName(name);
if (camera2) {
this.activeCamera = camera2;
return camera2;
}
return null;
};
Scene2.prototype.getAnimationGroupByName = function(name) {
for (var index = 0; index < this.animationGroups.length; index++) {
if (this.animationGroups[index].name === name) {
return this.animationGroups[index];
}
}
return null;
};
Scene2.prototype.getMaterialByID = function(id) {
for (var index = 0; index < this.materials.length; index++) {
if (this.materials[index].id === id) {
return this.materials[index];
}
}
return null;
};
Scene2.prototype.getMaterialByName = function(name) {
for (var index = 0; index < this.materials.length; index++) {
if (this.materials[index].name === name) {
return this.materials[index];
}
}
return null;
};
Scene2.prototype.getCameraByID = function(id) {
for (var index = 0; index < this.cameras.length; index++) {
if (this.cameras[index].id === id) {
return this.cameras[index];
}
}
return null;
};
Scene2.prototype.getCameraByUniqueID = function(uniqueId) {
for (var index = 0; index < this.cameras.length; index++) {
if (this.cameras[index].uniqueId === uniqueId) {
return this.cameras[index];
}
}
return null;
};
Scene2.prototype.getCameraByName = function(name) {
for (var index = 0; index < this.cameras.length; index++) {
if (this.cameras[index].name === name) {
return this.cameras[index];
}
}
return null;
};
Scene2.prototype.getBoneByID = function(id) {
for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
var skeleton = this.skeletons[skeletonIndex];
for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
if (skeleton.bones[boneIndex].id === id) {
return skeleton.bones[boneIndex];
}
}
}
return null;
};
Scene2.prototype.getBoneByName = function(name) {
for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
var skeleton = this.skeletons[skeletonIndex];
for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
if (skeleton.bones[boneIndex].name === name) {
return skeleton.bones[boneIndex];
}
}
}
return null;
};
Scene2.prototype.getLightByName = function(name) {
for (var index = 0; index < this.lights.length; index++) {
if (this.lights[index].name === name) {
return this.lights[index];
}
}
return null;
};
Scene2.prototype.getLightByID = function(id) {
for (var index = 0; index < this.lights.length; index++) {
if (this.lights[index].id === id) {
return this.lights[index];
}
}
return null;
};
Scene2.prototype.getLightByUniqueID = function(uniqueId) {
for (var index = 0; index < this.lights.length; index++) {
if (this.lights[index].uniqueId === uniqueId) {
return this.lights[index];
}
}
return null;
};
Scene2.prototype.getParticleSystemByID = function(id) {
for (var index = 0; index < this.particleSystems.length; index++) {
if (this.particleSystems[index].id === id) {
return this.particleSystems[index];
}
}
return null;
};
Scene2.prototype.getGeometryByID = function(id) {
for (var index = 0; index < this.geometries.length; index++) {
if (this.geometries[index].id === id) {
return this.geometries[index];
}
}
return null;
};
Scene2.prototype.pushGeometry = function(geometry, force) {
if (!force && this.getGeometryByID(geometry.id)) {
return false;
}
this.geometries.push(geometry);
if (this.collisionCoordinator) {
this.collisionCoordinator.onGeometryAdded(geometry);
}
this.onNewGeometryAddedObservable.notifyObservers(geometry);
return true;
};
Scene2.prototype.removeGeometry = function(geometry) {
var index = this.geometries.indexOf(geometry);
if (index > -1) {
this.geometries.splice(index, 1);
if (this.collisionCoordinator) {
this.collisionCoordinator.onGeometryDeleted(geometry);
}
this.onGeometryRemovedObservable.notifyObservers(geometry);
return true;
}
return false;
};
Scene2.prototype.getGeometries = function() {
return this.geometries;
};
Scene2.prototype.getMeshByID = function(id) {
for (var index = 0; index < this.meshes.length; index++) {
if (this.meshes[index].id === id) {
return this.meshes[index];
}
}
return null;
};
Scene2.prototype.getMeshesByID = function(id) {
return this.meshes.filter(function(m) {
return m.id === id;
});
};
Scene2.prototype.getTransformNodeByID = function(id) {
for (var index = 0; index < this.transformNodes.length; index++) {
if (this.transformNodes[index].id === id) {
return this.transformNodes[index];
}
}
return null;
};
Scene2.prototype.getTransformNodesByID = function(id) {
return this.transformNodes.filter(function(m) {
return m.id === id;
});
};
Scene2.prototype.getMeshByUniqueID = function(uniqueId) {
for (var index = 0; index < this.meshes.length; index++) {
if (this.meshes[index].uniqueId === uniqueId) {
return this.meshes[index];
}
}
return null;
};
Scene2.prototype.getLastMeshByID = function(id) {
for (var index = this.meshes.length - 1; index >= 0; index--) {
if (this.meshes[index].id === id) {
return this.meshes[index];
}
}
return null;
};
Scene2.prototype.getLastEntryByID = function(id) {
var index;
for (index = this.meshes.length - 1; index >= 0; index--) {
if (this.meshes[index].id === id) {
return this.meshes[index];
}
}
for (index = this.transformNodes.length - 1; index >= 0; index--) {
if (this.transformNodes[index].id === id) {
return this.transformNodes[index];
}
}
for (index = this.cameras.length - 1; index >= 0; index--) {
if (this.cameras[index].id === id) {
return this.cameras[index];
}
}
for (index = this.lights.length - 1; index >= 0; index--) {
if (this.lights[index].id === id) {
return this.lights[index];
}
}
return null;
};
Scene2.prototype.getNodeByID = function(id) {
var mesh2 = this.getMeshByID(id);
if (mesh2) {
return mesh2;
}
var light = this.getLightByID(id);
if (light) {
return light;
}
var camera2 = this.getCameraByID(id);
if (camera2) {
return camera2;
}
var bone = this.getBoneByID(id);
return bone;
};
Scene2.prototype.getNodeByName = function(name) {
var mesh2 = this.getMeshByName(name);
if (mesh2) {
return mesh2;
}
var light = this.getLightByName(name);
if (light) {
return light;
}
var camera2 = this.getCameraByName(name);
if (camera2) {
return camera2;
}
var bone = this.getBoneByName(name);
return bone;
};
Scene2.prototype.getMeshByName = function(name) {
for (var index = 0; index < this.meshes.length; index++) {
if (this.meshes[index].name === name) {
return this.meshes[index];
}
}
return null;
};
Scene2.prototype.getTransformNodeByName = function(name) {
for (var index = 0; index < this.transformNodes.length; index++) {
if (this.transformNodes[index].name === name) {
return this.transformNodes[index];
}
}
return null;
};
Scene2.prototype.getLastSkeletonByID = function(id) {
for (var index = this.skeletons.length - 1; index >= 0; index--) {
if (this.skeletons[index].id === id) {
return this.skeletons[index];
}
}
return null;
};
Scene2.prototype.getSkeletonById = function(id) {
for (var index = 0; index < this.skeletons.length; index++) {
if (this.skeletons[index].id === id) {
return this.skeletons[index];
}
}
return null;
};
Scene2.prototype.getSkeletonByName = function(name) {
for (var index = 0; index < this.skeletons.length; index++) {
if (this.skeletons[index].name === name) {
return this.skeletons[index];
}
}
return null;
};
Scene2.prototype.getMorphTargetManagerById = function(id) {
for (var index = 0; index < this.morphTargetManagers.length; index++) {
if (this.morphTargetManagers[index].uniqueId === id) {
return this.morphTargetManagers[index];
}
}
return null;
};
Scene2.prototype.isActiveMesh = function(mesh2) {
return this._activeMeshes.indexOf(mesh2) !== -1;
};
Object.defineProperty(Scene2.prototype, "uid", {
/**
* Return a unique id as a string which can serve as an identifier for the scene
*/
get: function() {
if (!this._uid) {
this._uid = BABYLON2.Tools.RandomId();
}
return this._uid;
},
enumerable: true,
configurable: true
});
Scene2.prototype.addExternalData = function(key, data2) {
if (!this._externalData) {
this._externalData = new BABYLON2.StringDictionary();
}
return this._externalData.add(key, data2);
};
Scene2.prototype.getExternalData = function(key) {
if (!this._externalData) {
return null;
}
return this._externalData.get(key);
};
Scene2.prototype.getOrAddExternalDataWithFactory = function(key, factory) {
if (!this._externalData) {
this._externalData = new BABYLON2.StringDictionary();
}
return this._externalData.getOrAddWithFactory(key, factory);
};
Scene2.prototype.removeExternalData = function(key) {
return this._externalData.remove(key);
};
Scene2.prototype._evaluateSubMesh = function(subMesh, mesh2) {
if (this.dispatchAllSubMeshesOfActiveMeshes || mesh2.alwaysSelectAsActiveMesh || mesh2.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
var step = _a[_i];
step.action(mesh2, subMesh);
}
var material = subMesh.getMaterial();
if (material !== null && material !== void 0) {
if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== void 0) {
if (this._processedMaterials.indexOf(material) === -1) {
this._processedMaterials.push(material);
this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
}
}
this._activeIndices.addCount(subMesh.indexCount, false);
this._renderingManager.dispatch(subMesh, mesh2, material);
}
}
};
Scene2.prototype.freeProcessedMaterials = function() {
this._processedMaterials.dispose();
};
Scene2.prototype.freeActiveMeshes = function() {
this._activeMeshes.dispose();
if (this.activeCamera && this.activeCamera._activeMeshes) {
this.activeCamera._activeMeshes.dispose();
}
if (this.activeCameras) {
for (var i2 = 0; i2 < this.activeCameras.length; i2++) {
var activeCamera = this.activeCameras[i2];
if (activeCamera && activeCamera._activeMeshes) {
activeCamera._activeMeshes.dispose();
}
}
}
};
Scene2.prototype.freeRenderingGroups = function() {
if (this._renderingManager) {
this._renderingManager.freeRenderingGroups();
}
if (this.textures) {
for (var i2 = 0; i2 < this.textures.length; i2++) {
var texture = this.textures[i2];
if (texture && texture.renderList) {
texture.freeRenderingGroups();
}
}
}
};
Scene2.prototype._isInIntermediateRendering = function() {
return this._intermediateRendering;
};
Scene2.prototype.freezeActiveMeshes = function() {
if (!this.activeCamera) {
return this;
}
if (!this._frustumPlanes) {
this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
}
this._evaluateActiveMeshes();
this._activeMeshesFrozen = true;
return this;
};
Scene2.prototype.unfreezeActiveMeshes = function() {
this._activeMeshesFrozen = false;
return this;
};
Scene2.prototype._evaluateActiveMeshes = function() {
if (this._activeMeshesFrozen && this._activeMeshes.length) {
return;
}
if (!this.activeCamera) {
return;
}
this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
this.activeCamera._activeMeshes.reset();
this._activeMeshes.reset();
this._renderingManager.reset();
this._processedMaterials.reset();
this._activeParticleSystems.reset();
this._activeSkeletons.reset();
this._softwareSkinnedMeshes.reset();
for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
var step = _a[_i];
step.action();
}
var meshes = this.getActiveMeshCandidates();
var len = meshes.length;
for (var i2 = 0; i2 < len; i2++) {
var mesh2 = meshes.data[i2];
if (mesh2.isBlocked) {
continue;
}
this._totalVertices.addCount(mesh2.getTotalVertices(), false);
if (!mesh2.isReady() || !mesh2.isEnabled()) {
continue;
}
mesh2.computeWorldMatrix();
if (mesh2.actionManager && mesh2.actionManager.hasSpecificTriggers2(BABYLON2.ActionManager.OnIntersectionEnterTrigger, BABYLON2.ActionManager.OnIntersectionExitTrigger)) {
this._meshesForIntersections.pushNoDuplicate(mesh2);
}
var meshLOD = mesh2.getLOD(this.activeCamera);
if (meshLOD === void 0 || meshLOD === null) {
continue;
}
mesh2._preActivate();
if (mesh2.isVisible && mesh2.visibility > 0 && (mesh2.alwaysSelectAsActiveMesh || (mesh2.layerMask & this.activeCamera.layerMask) !== 0 && mesh2.isInFrustum(this._frustumPlanes))) {
this._activeMeshes.push(mesh2);
this.activeCamera._activeMeshes.push(mesh2);
mesh2._activate(this._renderId);
if (meshLOD !== mesh2) {
meshLOD._activate(this._renderId);
}
this._activeMesh(mesh2, meshLOD);
}
}
this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
if (this.particlesEnabled) {
this.onBeforeParticlesRenderingObservable.notifyObservers(this);
for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
var particleSystem = this.particleSystems[particleIndex];
if (!particleSystem.isStarted() || !particleSystem.emitter) {
continue;
}
var emitter = particleSystem.emitter;
if (!emitter.position || emitter.isEnabled()) {
this._activeParticleSystems.push(particleSystem);
particleSystem.animate();
this._renderingManager.dispatchParticles(particleSystem);
}
}
this.onAfterParticlesRenderingObservable.notifyObservers(this);
}
};
Scene2.prototype._activeMesh = function(sourceMesh, mesh2) {
if (this._skeletonsEnabled && mesh2.skeleton !== null && mesh2.skeleton !== void 0) {
if (this._activeSkeletons.pushNoDuplicate(mesh2.skeleton)) {
mesh2.skeleton.prepare();
}
if (!mesh2.computeBonesUsingShaders) {
this._softwareSkinnedMeshes.pushNoDuplicate(mesh2);
}
}
for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
var step = _a[_i];
step.action(sourceMesh, mesh2);
}
if (mesh2 !== void 0 && mesh2 !== null && mesh2.subMeshes !== void 0 && mesh2.subMeshes !== null && mesh2.subMeshes.length > 0) {
var subMeshes = this.getActiveSubMeshCandidates(mesh2);
var len = subMeshes.length;
for (var i2 = 0; i2 < len; i2++) {
var subMesh = subMeshes.data[i2];
this._evaluateSubMesh(subMesh, mesh2);
}
}
};
Scene2.prototype.updateTransformMatrix = function(force) {
if (!this.activeCamera) {
return;
}
this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
};
Scene2.prototype.updateAlternateTransformMatrix = function(alternateCamera) {
this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
};
Scene2.prototype._renderForCamera = function(camera2, rigParent) {
if (camera2 && camera2._skipRendering) {
return;
}
var engine = this._engine;
this.activeCamera = camera2;
if (!this.activeCamera) {
throw new Error("Active camera not set");
}
engine.setViewport(this.activeCamera.viewport);
this.resetCachedMaterial();
this._renderId++;
this.updateTransformMatrix();
if (camera2._alternateCamera) {
this.updateAlternateTransformMatrix(camera2._alternateCamera);
this._alternateRendering = true;
}
this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
this._evaluateActiveMeshes();
for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
var mesh2 = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
mesh2.applySkeleton(mesh2.skeleton);
}
this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
if (camera2.customRenderTargets && camera2.customRenderTargets.length > 0) {
this._renderTargets.concatWithNoDuplicate(camera2.customRenderTargets);
}
if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
}
for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
var step = _a[_i];
step.action(this._renderTargets);
}
if (this.renderTargetsEnabled) {
this._intermediateRendering = true;
if (this._renderTargets.length > 0) {
BABYLON2.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
var renderTarget = this._renderTargets.data[renderIndex];
if (renderTarget._shouldRender()) {
this._renderId++;
var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
}
}
BABYLON2.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
this._renderId++;
}
for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
var step = _c[_b];
step.action(this.activeCamera);
}
this._intermediateRendering = false;
engine.restoreDefaultFramebuffer();
}
this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
if (this.postProcessManager) {
this.postProcessManager._prepareFrame();
}
for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
var step = _e[_d];
step.action(this.activeCamera);
}
this.onBeforeDrawPhaseObservable.notifyObservers(this);
this._renderingManager.render(null, null, true, true);
this.onAfterDrawPhaseObservable.notifyObservers(this);
for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
var step = _g[_f];
step.action(this.activeCamera);
}
if (this.postProcessManager) {
this.postProcessManager._finalizeFrame(camera2.isIntermediate);
}
this._renderTargets.reset();
this._alternateRendering = false;
this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
};
Scene2.prototype._processSubCameras = function(camera2) {
if (camera2.cameraRigMode === BABYLON2.Camera.RIG_MODE_NONE) {
this._renderForCamera(camera2);
return;
}
for (var index = 0; index < camera2._rigCameras.length; index++) {
this._renderForCamera(camera2._rigCameras[index], camera2);
}
this.activeCamera = camera2;
this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
};
Scene2.prototype._checkIntersections = function() {
for (var index = 0; index < this._meshesForIntersections.length; index++) {
var sourceMesh = this._meshesForIntersections.data[index];
if (!sourceMesh.actionManager) {
continue;
}
for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
var action = sourceMesh.actionManager.actions[actionIndex];
if (action.trigger === BABYLON2.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON2.ActionManager.OnIntersectionExitTrigger) {
var parameters = action.getTriggerParameter();
var otherMesh = parameters instanceof BABYLON2.AbstractMesh ? parameters : parameters.mesh;
var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
if (areIntersecting && currentIntersectionInProgress === -1) {
if (action.trigger === BABYLON2.ActionManager.OnIntersectionEnterTrigger) {
action._executeCurrent(BABYLON2.ActionEvent.CreateNew(sourceMesh, void 0, otherMesh));
sourceMesh._intersectionsInProgress.push(otherMesh);
} else if (action.trigger === BABYLON2.ActionManager.OnIntersectionExitTrigger) {
sourceMesh._intersectionsInProgress.push(otherMesh);
}
} else if (!areIntersecting && currentIntersectionInProgress > -1) {
if (action.trigger === BABYLON2.ActionManager.OnIntersectionExitTrigger) {
action._executeCurrent(BABYLON2.ActionEvent.CreateNew(sourceMesh, void 0, otherMesh));
}
if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON2.ActionManager.OnIntersectionExitTrigger, function(parameter) {
var parameterMesh = parameter instanceof BABYLON2.AbstractMesh ? parameter : parameter.mesh;
return otherMesh === parameterMesh;
}) || action.trigger === BABYLON2.ActionManager.OnIntersectionExitTrigger) {
sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
}
}
}
}
}
};
Scene2.prototype._advancePhysicsEngineStep = function(step) {
};
Scene2.prototype.render = function(updateCameras) {
if (updateCameras === void 0) {
updateCameras = true;
}
if (this.isDisposed) {
return;
}
this._frameId++;
this._registerTransientComponents();
this._activeParticles.fetchNewFrame();
this._totalVertices.fetchNewFrame();
this._activeIndices.fetchNewFrame();
this._activeBones.fetchNewFrame();
this._meshesForIntersections.reset();
this.resetCachedMaterial();
this.onBeforeAnimationsObservable.notifyObservers(this);
if (this.actionManager) {
this.actionManager.processTrigger(BABYLON2.ActionManager.OnEveryFrameTrigger);
}
if (this._engine.isDeterministicLockStep()) {
var deltaTime = Math.max(Scene2.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene2.MaxDeltaTime)) + this._timeAccumulator;
var defaultFPS = 60 / 1e3;
var defaultFrameTime = this.getDeterministicFrameTime();
var stepsTaken = 0;
var maxSubSteps = this._engine.getLockstepMaxSteps();
var internalSteps = Math.floor(deltaTime / (1e3 * defaultFPS));
internalSteps = Math.min(internalSteps, maxSubSteps);
do {
this.onBeforeStepObservable.notifyObservers(this);
this._animationRatio = defaultFrameTime * defaultFPS;
this._animate();
this.onAfterAnimationsObservable.notifyObservers(this);
this._advancePhysicsEngineStep(defaultFrameTime);
this.onAfterStepObservable.notifyObservers(this);
this._currentStepId++;
stepsTaken++;
deltaTime -= defaultFrameTime;
} while (deltaTime > 0 && stepsTaken < internalSteps);
this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
} else {
var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene2.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene2.MaxDeltaTime));
this._animationRatio = deltaTime * (60 / 1e3);
this._animate();
this.onAfterAnimationsObservable.notifyObservers(this);
this._advancePhysicsEngineStep(deltaTime);
}
for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
var step = _a[_i];
step.action();
}
if (updateCameras) {
if (this.activeCameras.length > 0) {
for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
var camera2 = this.activeCameras[cameraIndex];
camera2.update();
if (camera2.cameraRigMode !== BABYLON2.Camera.RIG_MODE_NONE) {
for (var index = 0; index < camera2._rigCameras.length; index++) {
camera2._rigCameras[index].update();
}
}
}
} else if (this.activeCamera) {
this.activeCamera.update();
if (this.activeCamera.cameraRigMode !== BABYLON2.Camera.RIG_MODE_NONE) {
for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
this.activeCamera._rigCameras[index].update();
}
}
}
}
this.onBeforeRenderObservable.notifyObservers(this);
this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
var engine = this.getEngine();
var currentActiveCamera = this.activeCamera;
if (this.renderTargetsEnabled) {
BABYLON2.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
this._intermediateRendering = true;
for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
var renderTarget = this.customRenderTargets[customIndex];
if (renderTarget._shouldRender()) {
this._renderId++;
this.activeCamera = renderTarget.activeCamera || this.activeCamera;
if (!this.activeCamera) {
throw new Error("Active camera not set");
}
engine.setViewport(this.activeCamera.viewport);
this.updateTransformMatrix();
renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
}
}
BABYLON2.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
this._intermediateRendering = false;
this._renderId++;
}
if (this.customRenderTargets.length > 0) {
engine.restoreDefaultFramebuffer();
}
this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
this.activeCamera = currentActiveCamera;
for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
var step = _c[_b];
step.action();
}
if (this.autoClearDepthAndStencil || this.autoClear) {
this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
}
for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
var step = _e[_d];
step.action(this._renderTargets);
}
if (this.activeCameras.length > 0) {
for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
if (cameraIndex > 0 && this.activeCameras[cameraIndex].autoClear) {
this._engine.clear(null, false, true, true);
}
this._processSubCameras(this.activeCameras[cameraIndex]);
}
} else {
if (!this.activeCamera) {
throw new Error("No camera defined");
}
this._processSubCameras(this.activeCamera);
}
this._checkIntersections();
for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
var step = _g[_f];
step.action();
}
if (this.afterRender) {
this.afterRender();
}
this.onAfterRenderObservable.notifyObservers(this);
if (this._toBeDisposed.length) {
for (var index = 0; index < this._toBeDisposed.length; index++) {
var data2 = this._toBeDisposed[index];
if (data2) {
data2.dispose();
}
}
this._toBeDisposed = [];
}
if (this.dumpNextRenderTargets) {
this.dumpNextRenderTargets = false;
}
this._activeBones.addCount(0, true);
this._activeIndices.addCount(0, true);
this._activeParticles.addCount(0, true);
};
Scene2.prototype.freezeMaterials = function() {
for (var i2 = 0; i2 < this.materials.length; i2++) {
this.materials[i2].freeze();
}
};
Scene2.prototype.unfreezeMaterials = function() {
for (var i2 = 0; i2 < this.materials.length; i2++) {
this.materials[i2].unfreeze();
}
};
Scene2.prototype.dispose = function() {
this.beforeRender = null;
this.afterRender = null;
this.skeletons = [];
this.morphTargetManagers = [];
this._transientComponents = [];
this._isReadyForMeshStage.clear();
this._beforeEvaluateActiveMeshStage.clear();
this._evaluateSubMeshStage.clear();
this._activeMeshStage.clear();
this._cameraDrawRenderTargetStage.clear();
this._beforeCameraDrawStage.clear();
this._beforeRenderingGroupDrawStage.clear();
this._beforeRenderingMeshStage.clear();
this._afterRenderingMeshStage.clear();
this._afterRenderingGroupDrawStage.clear();
this._afterCameraDrawStage.clear();
this._afterRenderStage.clear();
this._beforeCameraUpdateStage.clear();
this._beforeClearStage.clear();
this._gatherRenderTargetsStage.clear();
this._gatherActiveCameraRenderTargetsStage.clear();
this._pointerMoveStage.clear();
this._pointerDownStage.clear();
this._pointerUpStage.clear();
for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
var component = _a[_i];
component.dispose();
}
this.importedMeshesFiles = new Array();
this.stopAllAnimations();
this.resetCachedMaterial();
if (this.activeCamera) {
this.activeCamera._activeMeshes.dispose();
this.activeCamera = null;
}
this._activeMeshes.dispose();
this._renderingManager.dispose();
this._processedMaterials.dispose();
this._activeParticleSystems.dispose();
this._activeSkeletons.dispose();
this._softwareSkinnedMeshes.dispose();
this._renderTargets.dispose();
this._registeredForLateAnimationBindings.dispose();
this._meshesForIntersections.dispose();
this._toBeDisposed = [];
for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
var request = _c[_b];
request.abort();
}
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onBeforeRenderObservable.clear();
this.onAfterRenderObservable.clear();
this.onBeforeRenderTargetsRenderObservable.clear();
this.onAfterRenderTargetsRenderObservable.clear();
this.onAfterStepObservable.clear();
this.onBeforeStepObservable.clear();
this.onBeforeActiveMeshesEvaluationObservable.clear();
this.onAfterActiveMeshesEvaluationObservable.clear();
this.onBeforeParticlesRenderingObservable.clear();
this.onAfterParticlesRenderingObservable.clear();
this.onBeforeDrawPhaseObservable.clear();
this.onAfterDrawPhaseObservable.clear();
this.onBeforeAnimationsObservable.clear();
this.onAfterAnimationsObservable.clear();
this.onDataLoadedObservable.clear();
this.onBeforeRenderingGroupObservable.clear();
this.onAfterRenderingGroupObservable.clear();
this.onMeshImportedObservable.clear();
this.onBeforeCameraRenderObservable.clear();
this.onAfterCameraRenderObservable.clear();
this.onReadyObservable.clear();
this.onNewCameraAddedObservable.clear();
this.onCameraRemovedObservable.clear();
this.onNewLightAddedObservable.clear();
this.onLightRemovedObservable.clear();
this.onNewGeometryAddedObservable.clear();
this.onGeometryRemovedObservable.clear();
this.onNewTransformNodeAddedObservable.clear();
this.onTransformNodeRemovedObservable.clear();
this.onNewMeshAddedObservable.clear();
this.onMeshRemovedObservable.clear();
this.onNewMaterialAddedObservable.clear();
this.onMaterialRemovedObservable.clear();
this.onNewTextureAddedObservable.clear();
this.onTextureRemovedObservable.clear();
this.onPrePointerObservable.clear();
this.onPointerObservable.clear();
this.onPreKeyboardObservable.clear();
this.onKeyboardObservable.clear();
this.detachControl();
var canvas2 = this._engine.getRenderingCanvas();
if (canvas2) {
var index;
for (index = 0; index < this.cameras.length; index++) {
this.cameras[index].detachControl(canvas2);
}
}
while (this.animationGroups.length) {
this.animationGroups[0].dispose();
}
while (this.lights.length) {
this.lights[0].dispose();
}
while (this.meshes.length) {
this.meshes[0].dispose(true);
}
while (this.transformNodes.length) {
this.removeTransformNode(this.transformNodes[0]);
}
while (this.cameras.length) {
this.cameras[0].dispose();
}
if (this.defaultMaterial) {
this.defaultMaterial.dispose();
}
while (this.multiMaterials.length) {
this.multiMaterials[0].dispose();
}
while (this.materials.length) {
this.materials[0].dispose();
}
while (this.particleSystems.length) {
this.particleSystems[0].dispose();
}
while (this.postProcesses.length) {
this.postProcesses[0].dispose();
}
while (this.textures.length) {
this.textures[0].dispose();
}
this._sceneUbo.dispose();
if (this._alternateSceneUbo) {
this._alternateSceneUbo.dispose();
}
this.postProcessManager.dispose();
index = this._engine.scenes.indexOf(this);
if (index > -1) {
this._engine.scenes.splice(index, 1);
}
this._engine.wipeCaches(true);
this._isDisposed = true;
};
Object.defineProperty(Scene2.prototype, "isDisposed", {
/**
* Gets if the scene is already disposed
*/
get: function() {
return this._isDisposed;
},
enumerable: true,
configurable: true
});
Scene2.prototype.clearCachedVertexData = function() {
for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
var mesh2 = this.meshes[meshIndex];
var geometry = mesh2.geometry;
if (geometry) {
geometry._indices = [];
for (var vbName in geometry._vertexBuffers) {
if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
continue;
}
geometry._vertexBuffers[vbName]._buffer._data = null;
}
}
}
};
Scene2.prototype.cleanCachedTextureBuffer = function() {
for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
var baseTexture = _a[_i];
var buffer = baseTexture._buffer;
if (buffer) {
baseTexture._buffer = null;
}
}
};
Scene2.prototype.getWorldExtends = function(filterPredicate) {
var min = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var max = new BABYLON2.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
filterPredicate = filterPredicate || function() {
return true;
};
this.meshes.filter(filterPredicate).forEach(function(mesh2) {
mesh2.computeWorldMatrix(true);
if (!mesh2.subMeshes || mesh2.subMeshes.length === 0 || mesh2.infiniteDistance) {
return;
}
var boundingInfo = mesh2.getBoundingInfo();
var minBox = boundingInfo.boundingBox.minimumWorld;
var maxBox = boundingInfo.boundingBox.maximumWorld;
BABYLON2.Tools.CheckExtends(minBox, min, max);
BABYLON2.Tools.CheckExtends(maxBox, min, max);
});
return {
min,
max
};
};
Scene2.prototype.createPickingRay = function(x, y, world, camera2, cameraViewSpace) {
if (cameraViewSpace === void 0) {
cameraViewSpace = false;
}
var result = BABYLON2.Ray.Zero();
this.createPickingRayToRef(x, y, world, result, camera2, cameraViewSpace);
return result;
};
Scene2.prototype.createPickingRayToRef = function(x, y, world, result, camera2, cameraViewSpace) {
if (cameraViewSpace === void 0) {
cameraViewSpace = false;
}
var engine = this._engine;
if (!camera2) {
if (!this.activeCamera) {
throw new Error("Active camera not set");
}
camera2 = this.activeCamera;
}
var cameraViewport = camera2.viewport;
var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
x = x / this._engine.getHardwareScalingLevel() - viewport.x;
y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON2.Matrix.Identity(), cameraViewSpace ? BABYLON2.Matrix.Identity() : camera2.getViewMatrix(), camera2.getProjectionMatrix());
return this;
};
Scene2.prototype.createPickingRayInCameraSpace = function(x, y, camera2) {
var result = BABYLON2.Ray.Zero();
this.createPickingRayInCameraSpaceToRef(x, y, result, camera2);
return result;
};
Scene2.prototype.createPickingRayInCameraSpaceToRef = function(x, y, result, camera2) {
if (!BABYLON2.PickingInfo) {
return this;
}
var engine = this._engine;
if (!camera2) {
if (!this.activeCamera) {
throw new Error("Active camera not set");
}
camera2 = this.activeCamera;
}
var cameraViewport = camera2.viewport;
var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
var identity = BABYLON2.Matrix.Identity();
x = x / this._engine.getHardwareScalingLevel() - viewport.x;
y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
result.update(x, y, viewport.width, viewport.height, identity, identity, camera2.getProjectionMatrix());
return this;
};
Scene2.prototype._internalPick = function(rayFunction, predicate, fastCheck) {
if (!BABYLON2.PickingInfo) {
return null;
}
var pickingInfo = null;
for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
var mesh2 = this.meshes[meshIndex];
if (predicate) {
if (!predicate(mesh2)) {
continue;
}
} else if (!mesh2.isEnabled() || !mesh2.isVisible || !mesh2.isPickable) {
continue;
}
var world = mesh2.getWorldMatrix();
var ray = rayFunction(world);
var result = mesh2.intersects(ray, fastCheck);
if (!result || !result.hit) {
continue;
}
if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
continue;
}
pickingInfo = result;
if (fastCheck) {
break;
}
}
return pickingInfo || new BABYLON2.PickingInfo();
};
Scene2.prototype._internalMultiPick = function(rayFunction, predicate) {
if (!BABYLON2.PickingInfo) {
return null;
}
var pickingInfos = new Array();
for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
var mesh2 = this.meshes[meshIndex];
if (predicate) {
if (!predicate(mesh2)) {
continue;
}
} else if (!mesh2.isEnabled() || !mesh2.isVisible || !mesh2.isPickable) {
continue;
}
var world = mesh2.getWorldMatrix();
var ray = rayFunction(world);
var result = mesh2.intersects(ray, false);
if (!result || !result.hit) {
continue;
}
pickingInfos.push(result);
}
return pickingInfos;
};
Scene2.prototype.pick = function(x, y, predicate, fastCheck, camera2) {
var _this = this;
if (!BABYLON2.PickingInfo) {
return null;
}
var result = this._internalPick(function(world) {
_this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera2 || null);
return _this._tempPickingRay;
}, predicate, fastCheck);
if (result) {
result.ray = this.createPickingRay(x, y, BABYLON2.Matrix.Identity(), camera2 || null);
}
return result;
};
Scene2.prototype.pickWithRay = function(ray, predicate, fastCheck) {
var _this = this;
var result = this._internalPick(function(world) {
if (!_this._pickWithRayInverseMatrix) {
_this._pickWithRayInverseMatrix = BABYLON2.Matrix.Identity();
}
world.invertToRef(_this._pickWithRayInverseMatrix);
if (!_this._cachedRayForTransform) {
_this._cachedRayForTransform = BABYLON2.Ray.Zero();
}
BABYLON2.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
return _this._cachedRayForTransform;
}, predicate, fastCheck);
if (result) {
result.ray = ray;
}
return result;
};
Scene2.prototype.multiPick = function(x, y, predicate, camera2) {
var _this = this;
return this._internalMultiPick(function(world) {
return _this.createPickingRay(x, y, world, camera2 || null);
}, predicate);
};
Scene2.prototype.multiPickWithRay = function(ray, predicate) {
var _this = this;
return this._internalMultiPick(function(world) {
if (!_this._pickWithRayInverseMatrix) {
_this._pickWithRayInverseMatrix = BABYLON2.Matrix.Identity();
}
world.invertToRef(_this._pickWithRayInverseMatrix);
if (!_this._cachedRayForTransform) {
_this._cachedRayForTransform = BABYLON2.Ray.Zero();
}
BABYLON2.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
return _this._cachedRayForTransform;
}, predicate);
};
Scene2.prototype.setPointerOverMesh = function(mesh2) {
if (this._pointerOverMesh === mesh2) {
return;
}
if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
this._pointerOverMesh.actionManager.processTrigger(BABYLON2.ActionManager.OnPointerOutTrigger, BABYLON2.ActionEvent.CreateNew(this._pointerOverMesh));
}
this._pointerOverMesh = mesh2;
if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
this._pointerOverMesh.actionManager.processTrigger(BABYLON2.ActionManager.OnPointerOverTrigger, BABYLON2.ActionEvent.CreateNew(this._pointerOverMesh));
}
};
Scene2.prototype.getPointerOverMesh = function() {
return this._pointerOverMesh;
};
Scene2.prototype._rebuildGeometries = function() {
for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
var geometry = _a[_i];
geometry._rebuild();
}
for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
var mesh2 = _c[_b];
mesh2._rebuild();
}
if (this.postProcessManager) {
this.postProcessManager._rebuild();
}
for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
var component = _e[_d];
component.rebuild();
}
for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
var system = _g[_f];
system.rebuild();
}
};
Scene2.prototype._rebuildTextures = function() {
for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
var texture = _a[_i];
texture._rebuild();
}
this.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
};
Scene2.prototype._getByTags = function(list, tagsQuery, forEach) {
if (tagsQuery === void 0) {
return list;
}
var listByTags = [];
forEach = forEach || function(item2) {
return;
};
for (var i2 in list) {
var item = list[i2];
if (BABYLON2.Tags && BABYLON2.Tags.MatchesQuery(item, tagsQuery)) {
listByTags.push(item);
forEach(item);
}
}
return listByTags;
};
Scene2.prototype.getMeshesByTags = function(tagsQuery, forEach) {
return this._getByTags(this.meshes, tagsQuery, forEach);
};
Scene2.prototype.getCamerasByTags = function(tagsQuery, forEach) {
return this._getByTags(this.cameras, tagsQuery, forEach);
};
Scene2.prototype.getLightsByTags = function(tagsQuery, forEach) {
return this._getByTags(this.lights, tagsQuery, forEach);
};
Scene2.prototype.getMaterialByTags = function(tagsQuery, forEach) {
return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
};
Scene2.prototype.setRenderingOrder = function(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
if (opaqueSortCompareFn === void 0) {
opaqueSortCompareFn = null;
}
if (alphaTestSortCompareFn === void 0) {
alphaTestSortCompareFn = null;
}
if (transparentSortCompareFn === void 0) {
transparentSortCompareFn = null;
}
this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
};
Scene2.prototype.setRenderingAutoClearDepthStencil = function(renderingGroupId, autoClearDepthStencil, depth, stencil) {
if (depth === void 0) {
depth = true;
}
if (stencil === void 0) {
stencil = true;
}
this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
};
Scene2.prototype.getAutoClearDepthStencilSetup = function(index) {
return this._renderingManager.getAutoClearDepthStencilSetup(index);
};
Object.defineProperty(Scene2.prototype, "blockMaterialDirtyMechanism", {
/** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
get: function() {
return this._blockMaterialDirtyMechanism;
},
set: function(value) {
if (this._blockMaterialDirtyMechanism === value) {
return;
}
this._blockMaterialDirtyMechanism = value;
if (!value) {
this.markAllMaterialsAsDirty(BABYLON2.Material.AllDirtyFlag);
}
},
enumerable: true,
configurable: true
});
Scene2.prototype.markAllMaterialsAsDirty = function(flag, predicate) {
if (this._blockMaterialDirtyMechanism) {
return;
}
for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
var material = _a[_i];
if (predicate && !predicate(material)) {
continue;
}
material.markAsDirty(flag);
}
};
Scene2.prototype._loadFile = function(url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
var _this = this;
var request = BABYLON2.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : void 0, useArrayBuffer, onError);
this._activeRequests.push(request);
request.onCompleteObservable.add(function(request2) {
_this._activeRequests.splice(_this._activeRequests.indexOf(request2), 1);
});
return request;
};
Scene2.prototype._loadFileAsync = function(url, useDatabase, useArrayBuffer) {
var _this = this;
return new Promise(function(resolve, reject) {
_this._loadFile(url, function(data2) {
resolve(data2);
}, void 0, useDatabase, useArrayBuffer, function(request, exception) {
reject(exception);
});
});
};
Scene2._uniqueIdCounter = 0;
Scene2.FOGMODE_NONE = 0;
Scene2.FOGMODE_EXP = 1;
Scene2.FOGMODE_EXP2 = 2;
Scene2.FOGMODE_LINEAR = 3;
Scene2.MinDeltaTime = 1;
Scene2.MaxDeltaTime = 1e3;
Scene2.DragMovementThreshold = 10;
Scene2.LongPressDelay = 500;
Scene2.DoubleClickDelay = 300;
Scene2.ExclusiveDoubleClickMode = false;
return Scene2;
}(BABYLON2.AbstractScene)
);
BABYLON2.Scene = Scene;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var KeepAssets = (
/** @class */
function(_super) {
__extends(KeepAssets2, _super);
function KeepAssets2() {
return _super !== null && _super.apply(this, arguments) || this;
}
return KeepAssets2;
}(BABYLON2.AbstractScene)
);
BABYLON2.KeepAssets = KeepAssets;
var AssetContainer = (
/** @class */
function(_super) {
__extends(AssetContainer2, _super);
function AssetContainer2(scene) {
var _this = _super.call(this) || this;
_this.scene = scene;
return _this;
}
AssetContainer2.prototype.addAllToScene = function() {
var _this = this;
this.cameras.forEach(function(o) {
_this.scene.addCamera(o);
});
this.lights.forEach(function(o) {
_this.scene.addLight(o);
});
this.meshes.forEach(function(o) {
_this.scene.addMesh(o);
});
this.skeletons.forEach(function(o) {
_this.scene.addSkeleton(o);
});
this.animations.forEach(function(o) {
_this.scene.addAnimation(o);
});
this.animationGroups.forEach(function(o) {
_this.scene.addAnimationGroup(o);
});
this.multiMaterials.forEach(function(o) {
_this.scene.addMultiMaterial(o);
});
this.materials.forEach(function(o) {
_this.scene.addMaterial(o);
});
this.morphTargetManagers.forEach(function(o) {
_this.scene.addMorphTargetManager(o);
});
this.geometries.forEach(function(o) {
_this.scene.addGeometry(o);
});
this.transformNodes.forEach(function(o) {
_this.scene.addTransformNode(o);
});
this.actionManagers.forEach(function(o) {
_this.scene.addActionManager(o);
});
this.textures.forEach(function(o) {
_this.scene.addTexture(o);
});
for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
var component = _a[_i];
component.addFromContainer(this.scene);
}
};
AssetContainer2.prototype.removeAllFromScene = function() {
var _this = this;
this.cameras.forEach(function(o) {
_this.scene.removeCamera(o);
});
this.lights.forEach(function(o) {
_this.scene.removeLight(o);
});
this.meshes.forEach(function(o) {
_this.scene.removeMesh(o);
});
this.skeletons.forEach(function(o) {
_this.scene.removeSkeleton(o);
});
this.animations.forEach(function(o) {
_this.scene.removeAnimation(o);
});
this.animationGroups.forEach(function(o) {
_this.scene.removeAnimationGroup(o);
});
this.multiMaterials.forEach(function(o) {
_this.scene.removeMultiMaterial(o);
});
this.materials.forEach(function(o) {
_this.scene.removeMaterial(o);
});
this.morphTargetManagers.forEach(function(o) {
_this.scene.removeMorphTargetManager(o);
});
this.geometries.forEach(function(o) {
_this.scene.removeGeometry(o);
});
this.transformNodes.forEach(function(o) {
_this.scene.removeTransformNode(o);
});
this.actionManagers.forEach(function(o) {
_this.scene.removeActionManager(o);
});
this.textures.forEach(function(o) {
_this.scene.removeTexture(o);
});
for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
var component = _a[_i];
component.removeFromContainer(this.scene);
}
};
AssetContainer2.prototype._moveAssets = function(sourceAssets, targetAssets, keepAssets) {
if (!sourceAssets) {
return;
}
for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
var asset = sourceAssets_1[_i];
var move = true;
if (keepAssets) {
for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
var keepAsset = keepAssets_1[_a];
if (asset === keepAsset) {
move = false;
break;
}
}
}
if (move) {
targetAssets.push(asset);
}
}
};
AssetContainer2.prototype.moveAllFromScene = function(keepAssets) {
if (keepAssets === void 0) {
keepAssets = new KeepAssets();
}
for (var key in this) {
if (this.hasOwnProperty(key)) {
this[key] = this[key] || [];
this._moveAssets(this.scene[key], this[key], keepAssets[key]);
}
}
this.removeAllFromScene();
};
AssetContainer2.prototype.createRootMesh = function() {
var rootMesh = new BABYLON2.Mesh("assetContainerRootMesh", this.scene);
this.meshes.forEach(function(m) {
if (!m.parent) {
rootMesh.addChild(m);
}
});
this.meshes.unshift(rootMesh);
return rootMesh;
};
return AssetContainer2;
}(BABYLON2.AbstractScene)
);
BABYLON2.AssetContainer = AssetContainer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Buffer2 = (
/** @class */
function() {
function Buffer3(engine, data2, updatable, stride, postponeInternalCreation, instanced, useBytes) {
if (stride === void 0) {
stride = 0;
}
if (postponeInternalCreation === void 0) {
postponeInternalCreation = false;
}
if (instanced === void 0) {
instanced = false;
}
if (useBytes === void 0) {
useBytes = false;
}
if (engine instanceof BABYLON2.Mesh) {
this._engine = engine.getScene().getEngine();
} else {
this._engine = engine;
}
this._updatable = updatable;
this._instanced = instanced;
this._data = data2;
this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
if (!postponeInternalCreation) {
this.create();
}
}
Buffer3.prototype.createVertexBuffer = function(kind, offset, size, stride, instanced, useBytes) {
if (useBytes === void 0) {
useBytes = false;
}
var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
var byteStride = stride ? useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT : this.byteStride;
return new BABYLON2.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === void 0 ? this._instanced : instanced, byteOffset, size, void 0, void 0, true);
};
Buffer3.prototype.isUpdatable = function() {
return this._updatable;
};
Buffer3.prototype.getData = function() {
return this._data;
};
Buffer3.prototype.getBuffer = function() {
return this._buffer;
};
Buffer3.prototype.getStrideSize = function() {
return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
};
Buffer3.prototype.create = function(data2) {
if (data2 === void 0) {
data2 = null;
}
if (!data2 && this._buffer) {
return;
}
data2 = data2 || this._data;
if (!data2) {
return;
}
if (!this._buffer) {
if (this._updatable) {
this._buffer = this._engine.createDynamicVertexBuffer(data2);
this._data = data2;
} else {
this._buffer = this._engine.createVertexBuffer(data2);
}
} else if (this._updatable) {
this._engine.updateDynamicVertexBuffer(this._buffer, data2);
this._data = data2;
}
};
Buffer3.prototype._rebuild = function() {
this._buffer = null;
this.create(this._data);
};
Buffer3.prototype.update = function(data2) {
this.create(data2);
};
Buffer3.prototype.updateDirectly = function(data2, offset, vertexCount, useBytes) {
if (useBytes === void 0) {
useBytes = false;
}
if (!this._buffer) {
return;
}
if (this._updatable) {
this._engine.updateDynamicVertexBuffer(this._buffer, data2, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : void 0);
this._data = null;
}
};
Buffer3.prototype.dispose = function() {
if (!this._buffer) {
return;
}
if (this._engine._releaseBuffer(this._buffer)) {
this._buffer = null;
}
};
return Buffer3;
}()
);
BABYLON2.Buffer = Buffer2;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var VertexBuffer = (
/** @class */
function() {
function VertexBuffer2(engine, data2, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
if (normalized === void 0) {
normalized = false;
}
if (useBytes === void 0) {
useBytes = false;
}
if (data2 instanceof BABYLON2.Buffer) {
this._buffer = data2;
this._ownsBuffer = false;
} else {
this._buffer = new BABYLON2.Buffer(engine, data2, updatable, stride, postponeInternalCreation, instanced, useBytes);
this._ownsBuffer = true;
}
this._kind = kind;
if (type == void 0) {
var data_1 = this.getData();
this.type = VertexBuffer2.FLOAT;
if (data_1 instanceof Int8Array) {
this.type = VertexBuffer2.BYTE;
} else if (data_1 instanceof Uint8Array) {
this.type = VertexBuffer2.UNSIGNED_BYTE;
} else if (data_1 instanceof Int16Array) {
this.type = VertexBuffer2.SHORT;
} else if (data_1 instanceof Uint16Array) {
this.type = VertexBuffer2.UNSIGNED_SHORT;
} else if (data_1 instanceof Int32Array) {
this.type = VertexBuffer2.INT;
} else if (data_1 instanceof Uint32Array) {
this.type = VertexBuffer2.UNSIGNED_INT;
}
} else {
this.type = type;
}
var typeByteLength = VertexBuffer2.GetTypeByteLength(this.type);
if (useBytes) {
this._size = size || (stride ? stride / typeByteLength : VertexBuffer2.DeduceStride(kind));
this.byteStride = stride || this._buffer.byteStride || this._size * typeByteLength;
this.byteOffset = offset || 0;
} else {
this._size = size || stride || VertexBuffer2.DeduceStride(kind);
this.byteStride = stride ? stride * typeByteLength : this._buffer.byteStride || this._size * typeByteLength;
this.byteOffset = (offset || 0) * typeByteLength;
}
this.normalized = normalized;
this._instanced = instanced !== void 0 ? instanced : false;
this._instanceDivisor = instanced ? 1 : 0;
}
Object.defineProperty(VertexBuffer2.prototype, "instanceDivisor", {
/**
* Gets or sets the instance divisor when in instanced mode
*/
get: function() {
return this._instanceDivisor;
},
set: function(value) {
this._instanceDivisor = value;
if (value == 0) {
this._instanced = false;
} else {
this._instanced = true;
}
},
enumerable: true,
configurable: true
});
VertexBuffer2.prototype._rebuild = function() {
if (!this._buffer) {
return;
}
this._buffer._rebuild();
};
VertexBuffer2.prototype.getKind = function() {
return this._kind;
};
VertexBuffer2.prototype.isUpdatable = function() {
return this._buffer.isUpdatable();
};
VertexBuffer2.prototype.getData = function() {
return this._buffer.getData();
};
VertexBuffer2.prototype.getBuffer = function() {
return this._buffer.getBuffer();
};
VertexBuffer2.prototype.getStrideSize = function() {
return this.byteStride / VertexBuffer2.GetTypeByteLength(this.type);
};
VertexBuffer2.prototype.getOffset = function() {
return this.byteOffset / VertexBuffer2.GetTypeByteLength(this.type);
};
VertexBuffer2.prototype.getSize = function() {
return this._size;
};
VertexBuffer2.prototype.getIsInstanced = function() {
return this._instanced;
};
VertexBuffer2.prototype.getInstanceDivisor = function() {
return this._instanceDivisor;
};
VertexBuffer2.prototype.create = function(data2) {
this._buffer.create(data2);
};
VertexBuffer2.prototype.update = function(data2) {
this._buffer.update(data2);
};
VertexBuffer2.prototype.updateDirectly = function(data2, offset, useBytes) {
if (useBytes === void 0) {
useBytes = false;
}
this._buffer.updateDirectly(data2, offset, void 0, useBytes);
};
VertexBuffer2.prototype.dispose = function() {
if (this._ownsBuffer) {
this._buffer.dispose();
}
};
VertexBuffer2.prototype.forEach = function(count, callback) {
VertexBuffer2.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
};
VertexBuffer2.DeduceStride = function(kind) {
switch (kind) {
case VertexBuffer2.UVKind:
case VertexBuffer2.UV2Kind:
case VertexBuffer2.UV3Kind:
case VertexBuffer2.UV4Kind:
case VertexBuffer2.UV5Kind:
case VertexBuffer2.UV6Kind:
return 2;
case VertexBuffer2.NormalKind:
case VertexBuffer2.PositionKind:
return 3;
case VertexBuffer2.ColorKind:
case VertexBuffer2.MatricesIndicesKind:
case VertexBuffer2.MatricesIndicesExtraKind:
case VertexBuffer2.MatricesWeightsKind:
case VertexBuffer2.MatricesWeightsExtraKind:
case VertexBuffer2.TangentKind:
return 4;
default:
throw new Error("Invalid kind '" + kind + "'");
}
};
VertexBuffer2.GetTypeByteLength = function(type) {
switch (type) {
case VertexBuffer2.BYTE:
case VertexBuffer2.UNSIGNED_BYTE:
return 1;
case VertexBuffer2.SHORT:
case VertexBuffer2.UNSIGNED_SHORT:
return 2;
case VertexBuffer2.INT:
case VertexBuffer2.FLOAT:
return 4;
default:
throw new Error("Invalid type '" + type + "'");
}
};
VertexBuffer2.ForEach = function(data2, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
if (data2 instanceof Array) {
var offset = byteOffset / 4;
var stride = byteStride / 4;
for (var index = 0; index < count; index += componentCount) {
for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
callback(data2[offset + componentIndex], index + componentIndex);
}
offset += stride;
}
} else {
var dataView = data2 instanceof ArrayBuffer ? new DataView(data2) : new DataView(data2.buffer, data2.byteOffset, data2.byteLength);
var componentByteLength = VertexBuffer2.GetTypeByteLength(componentType);
for (var index = 0; index < count; index += componentCount) {
var componentByteOffset = byteOffset;
for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
var value = VertexBuffer2._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
callback(value, index + componentIndex);
componentByteOffset += componentByteLength;
}
byteOffset += byteStride;
}
}
};
VertexBuffer2._GetFloatValue = function(dataView, type, byteOffset, normalized) {
switch (type) {
case VertexBuffer2.BYTE: {
var value = dataView.getInt8(byteOffset);
if (normalized) {
value = Math.max(value / 127, -1);
}
return value;
}
case VertexBuffer2.UNSIGNED_BYTE: {
var value = dataView.getUint8(byteOffset);
if (normalized) {
value = value / 255;
}
return value;
}
case VertexBuffer2.SHORT: {
var value = dataView.getInt16(byteOffset, true);
if (normalized) {
value = Math.max(value / 16383, -1);
}
return value;
}
case VertexBuffer2.UNSIGNED_SHORT: {
var value = dataView.getUint16(byteOffset, true);
if (normalized) {
value = value / 65535;
}
return value;
}
case VertexBuffer2.FLOAT: {
return dataView.getFloat32(byteOffset, true);
}
default: {
throw new Error("Invalid component type " + type);
}
}
};
VertexBuffer2.BYTE = 5120;
VertexBuffer2.UNSIGNED_BYTE = 5121;
VertexBuffer2.SHORT = 5122;
VertexBuffer2.UNSIGNED_SHORT = 5123;
VertexBuffer2.INT = 5124;
VertexBuffer2.UNSIGNED_INT = 5125;
VertexBuffer2.FLOAT = 5126;
VertexBuffer2.PositionKind = "position";
VertexBuffer2.NormalKind = "normal";
VertexBuffer2.TangentKind = "tangent";
VertexBuffer2.UVKind = "uv";
VertexBuffer2.UV2Kind = "uv2";
VertexBuffer2.UV3Kind = "uv3";
VertexBuffer2.UV4Kind = "uv4";
VertexBuffer2.UV5Kind = "uv5";
VertexBuffer2.UV6Kind = "uv6";
VertexBuffer2.ColorKind = "color";
VertexBuffer2.MatricesIndicesKind = "matricesIndices";
VertexBuffer2.MatricesWeightsKind = "matricesWeights";
VertexBuffer2.MatricesIndicesExtraKind = "matricesIndicesExtra";
VertexBuffer2.MatricesWeightsExtraKind = "matricesWeightsExtra";
return VertexBuffer2;
}()
);
BABYLON2.VertexBuffer = VertexBuffer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DummyInternalTextureTracker = (
/** @class */
function() {
function DummyInternalTextureTracker2() {
this.previous = null;
this.next = null;
}
return DummyInternalTextureTracker2;
}()
);
BABYLON2.DummyInternalTextureTracker = DummyInternalTextureTracker;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var InternalTexture = (
/** @class */
function() {
function InternalTexture2(engine, dataSource) {
this.onLoadedObservable = new BABYLON2.Observable();
this.previous = null;
this.next = null;
this._initialSlot = -1;
this._designatedSlot = -1;
this._dataSource = InternalTexture2.DATASOURCE_UNKNOWN;
this._comparisonFunction = 0;
this._sphericalPolynomial = null;
this._lodGenerationScale = 0;
this._lodGenerationOffset = 0;
this._isRGBD = false;
this._references = 1;
this._engine = engine;
this._dataSource = dataSource;
this._webGLTexture = engine._createTexture();
}
InternalTexture2.prototype.getEngine = function() {
return this._engine;
};
Object.defineProperty(InternalTexture2.prototype, "dataSource", {
/**
* Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
*/
get: function() {
return this._dataSource;
},
enumerable: true,
configurable: true
});
InternalTexture2.prototype.incrementReferences = function() {
this._references++;
};
InternalTexture2.prototype.updateSize = function(width, height, depth) {
if (depth === void 0) {
depth = 1;
}
this.width = width;
this.height = height;
this.depth = depth;
this.baseWidth = width;
this.baseHeight = height;
this.baseDepth = depth;
this._size = width * height * depth;
};
InternalTexture2.prototype._rebuild = function() {
var _this = this;
var proxy;
this.isReady = false;
this._cachedCoordinatesMode = null;
this._cachedWrapU = null;
this._cachedWrapV = null;
this._cachedAnisotropicFilteringLevel = null;
switch (this._dataSource) {
case InternalTexture2.DATASOURCE_TEMP:
return;
case InternalTexture2.DATASOURCE_URL:
proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function() {
_this.isReady = true;
}, null, this._buffer, void 0, this.format);
proxy._swapAndDie(this);
return;
case InternalTexture2.DATASOURCE_RAW:
proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture2.DATASOURCE_RAW3D:
proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture2.DATASOURCE_DYNAMIC:
proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
proxy._swapAndDie(this);
return;
case InternalTexture2.DATASOURCE_RENDERTARGET:
var options = new BABYLON2.RenderTargetCreationOptions();
options.generateDepthBuffer = this._generateDepthBuffer;
options.generateMipMaps = this.generateMipMaps;
options.generateStencilBuffer = this._generateStencilBuffer;
options.samplingMode = this.samplingMode;
options.type = this.type;
if (this.isCube) {
proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
} else {
var size = {
width: this.width,
height: this.height
};
proxy = this._engine.createRenderTargetTexture(size, options);
}
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture2.DATASOURCE_DEPTHTEXTURE:
var depthTextureOptions = {
bilinearFiltering: this.samplingMode !== BABYLON2.Texture.BILINEAR_SAMPLINGMODE,
comparisonFunction: this._comparisonFunction,
generateStencil: this._generateStencilBuffer,
isCube: this.isCube
};
proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture2.DATASOURCE_CUBE:
proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function() {
_this.isReady = true;
}, null, this.format, this._extension);
proxy._swapAndDie(this);
return;
case InternalTexture2.DATASOURCE_CUBERAW:
proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
proxy._swapAndDie(this);
this.isReady = true;
return;
case InternalTexture2.DATASOURCE_CUBERAW_RGBD:
proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
BABYLON2.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function() {
_this.isReady = true;
});
proxy._swapAndDie(this);
return;
case InternalTexture2.DATASOURCE_CUBEPREFILTERED:
proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function(proxy2) {
if (proxy2) {
proxy2._swapAndDie(_this);
}
_this.isReady = true;
}, null, this.format, this._extension);
proxy._sphericalPolynomial = this._sphericalPolynomial;
return;
}
};
InternalTexture2.prototype._swapAndDie = function(target) {
target._webGLTexture = this._webGLTexture;
if (this._framebuffer) {
target._framebuffer = this._framebuffer;
}
if (this._depthStencilBuffer) {
target._depthStencilBuffer = this._depthStencilBuffer;
}
if (this._lodTextureHigh) {
if (target._lodTextureHigh) {
target._lodTextureHigh.dispose();
}
target._lodTextureHigh = this._lodTextureHigh;
}
if (this._lodTextureMid) {
if (target._lodTextureMid) {
target._lodTextureMid.dispose();
}
target._lodTextureMid = this._lodTextureMid;
}
if (this._lodTextureLow) {
if (target._lodTextureLow) {
target._lodTextureLow.dispose();
}
target._lodTextureLow = this._lodTextureLow;
}
var cache = this._engine.getLoadedTexturesCache();
var index = cache.indexOf(this);
if (index !== -1) {
cache.splice(index, 1);
}
};
InternalTexture2.prototype.dispose = function() {
if (!this._webGLTexture) {
return;
}
this._references--;
if (this._references === 0) {
this._engine._releaseTexture(this);
this._webGLTexture = null;
this.previous = null;
this.next = null;
}
};
InternalTexture2.DATASOURCE_UNKNOWN = 0;
InternalTexture2.DATASOURCE_URL = 1;
InternalTexture2.DATASOURCE_TEMP = 2;
InternalTexture2.DATASOURCE_RAW = 3;
InternalTexture2.DATASOURCE_DYNAMIC = 4;
InternalTexture2.DATASOURCE_RENDERTARGET = 5;
InternalTexture2.DATASOURCE_MULTIRENDERTARGET = 6;
InternalTexture2.DATASOURCE_CUBE = 7;
InternalTexture2.DATASOURCE_CUBERAW = 8;
InternalTexture2.DATASOURCE_CUBEPREFILTERED = 9;
InternalTexture2.DATASOURCE_RAW3D = 10;
InternalTexture2.DATASOURCE_DEPTHTEXTURE = 11;
InternalTexture2.DATASOURCE_CUBERAW_RGBD = 12;
return InternalTexture2;
}()
);
BABYLON2.InternalTexture = InternalTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BaseTexture = (
/** @class */
function() {
function BaseTexture2(scene) {
this._hasAlpha = false;
this.getAlphaFromRGB = false;
this.level = 1;
this.coordinatesIndex = 0;
this._coordinatesMode = BABYLON2.Texture.EXPLICIT_MODE;
this.wrapU = BABYLON2.Texture.WRAP_ADDRESSMODE;
this.wrapV = BABYLON2.Texture.WRAP_ADDRESSMODE;
this.wrapR = BABYLON2.Texture.WRAP_ADDRESSMODE;
this.anisotropicFilteringLevel = BaseTexture2.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
this.isCube = false;
this.is3D = false;
this.gammaSpace = true;
this.invertZ = false;
this.lodLevelInAlpha = false;
this.isRenderTarget = false;
this.animations = new Array();
this.onDisposeObservable = new BABYLON2.Observable();
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NONE;
this._cachedSize = BABYLON2.Size.Zero();
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
if (this._scene) {
this._scene.textures.push(this);
this._scene.onNewTextureAddedObservable.notifyObservers(this);
}
this._uid = null;
}
Object.defineProperty(BaseTexture2.prototype, "hasAlpha", {
get: function() {
return this._hasAlpha;
},
/**
* Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
*/
set: function(value) {
if (this._hasAlpha === value) {
return;
}
this._hasAlpha = value;
if (this._scene) {
this._scene.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag | BABYLON2.Material.MiscDirtyFlag);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "coordinatesMode", {
get: function() {
return this._coordinatesMode;
},
/**
* How a texture is mapped.
*
* | Value | Type | Description |
* | ----- | ----------------------------------- | ----------- |
* | 0 | EXPLICIT_MODE | |
* | 1 | SPHERICAL_MODE | |
* | 2 | PLANAR_MODE | |
* | 3 | CUBIC_MODE | |
* | 4 | PROJECTION_MODE | |
* | 5 | SKYBOX_MODE | |
* | 6 | INVCUBIC_MODE | |
* | 7 | EQUIRECTANGULAR_MODE | |
* | 8 | FIXED_EQUIRECTANGULAR_MODE | |
* | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
*/
set: function(value) {
if (this._coordinatesMode === value) {
return;
}
this._coordinatesMode = value;
if (this._scene) {
this._scene.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "isRGBD", {
/**
* Gets whether or not the texture contains RGBD data.
*/
get: function() {
return this._texture != null && this._texture._isRGBD;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "lodGenerationOffset", {
/**
* With prefiltered texture, defined the offset used during the prefiltering steps.
*/
get: function() {
if (this._texture) {
return this._texture._lodGenerationOffset;
}
return 0;
},
set: function(value) {
if (this._texture) {
this._texture._lodGenerationOffset = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "lodGenerationScale", {
/**
* With prefiltered texture, defined the scale used during the prefiltering steps.
*/
get: function() {
if (this._texture) {
return this._texture._lodGenerationScale;
}
return 0;
},
set: function(value) {
if (this._texture) {
this._texture._lodGenerationScale = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "uid", {
/**
* Define the unique id of the texture in the scene.
*/
get: function() {
if (!this._uid) {
this._uid = BABYLON2.Tools.RandomId();
}
return this._uid;
},
enumerable: true,
configurable: true
});
BaseTexture2.prototype.toString = function() {
return this.name;
};
BaseTexture2.prototype.getClassName = function() {
return "BaseTexture";
};
Object.defineProperty(BaseTexture2.prototype, "onDispose", {
/**
* Callback triggered when the texture has been disposed.
* Kept for back compatibility, you can use the onDisposeObservable instead.
*/
set: function(callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "isBlocking", {
/**
* Define if the texture is preventinga material to render or not.
* If not and the texture is not ready, the engine will use a default black texture instead.
*/
get: function() {
return true;
},
enumerable: true,
configurable: true
});
BaseTexture2.prototype.getScene = function() {
return this._scene;
};
BaseTexture2.prototype.getTextureMatrix = function() {
return BABYLON2.Matrix.IdentityReadOnly;
};
BaseTexture2.prototype.getReflectionTextureMatrix = function() {
return BABYLON2.Matrix.IdentityReadOnly;
};
BaseTexture2.prototype.getInternalTexture = function() {
return this._texture;
};
BaseTexture2.prototype.isReadyOrNotBlocking = function() {
return !this.isBlocking || this.isReady();
};
BaseTexture2.prototype.isReady = function() {
if (this.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED) {
this.delayLoad();
return false;
}
if (this._texture) {
return this._texture.isReady;
}
return false;
};
BaseTexture2.prototype.getSize = function() {
if (this._texture) {
if (this._texture.width) {
this._cachedSize.width = this._texture.width;
this._cachedSize.height = this._texture.height;
return this._cachedSize;
}
if (this._texture._size) {
this._cachedSize.width = this._texture._size;
this._cachedSize.height = this._texture._size;
return this._cachedSize;
}
}
return this._cachedSize;
};
BaseTexture2.prototype.getBaseSize = function() {
if (!this.isReady() || !this._texture) {
return BABYLON2.Size.Zero();
}
if (this._texture._size) {
return new BABYLON2.Size(this._texture._size, this._texture._size);
}
return new BABYLON2.Size(this._texture.baseWidth, this._texture.baseHeight);
};
BaseTexture2.prototype.scale = function(ratio) {
};
Object.defineProperty(BaseTexture2.prototype, "canRescale", {
/**
* Get if the texture can rescale.
*/
get: function() {
return false;
},
enumerable: true,
configurable: true
});
BaseTexture2.prototype._getFromCache = function(url, noMipmap, sampling) {
if (!this._scene) {
return null;
}
var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
for (var index = 0; index < texturesCache.length; index++) {
var texturesCacheEntry = texturesCache[index];
if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
if (!sampling || sampling === texturesCacheEntry.samplingMode) {
texturesCacheEntry.incrementReferences();
return texturesCacheEntry;
}
}
}
return null;
};
BaseTexture2.prototype._rebuild = function() {
};
BaseTexture2.prototype.delayLoad = function() {
};
BaseTexture2.prototype.clone = function() {
return null;
};
Object.defineProperty(BaseTexture2.prototype, "textureType", {
/**
* Get the texture underlying type (INT, FLOAT...)
*/
get: function() {
if (!this._texture) {
return BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
return this._texture.type !== void 0 ? this._texture.type : BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "textureFormat", {
/**
* Get the texture underlying format (RGB, RGBA...)
*/
get: function() {
if (!this._texture) {
return BABYLON2.Engine.TEXTUREFORMAT_RGBA;
}
return this._texture.format !== void 0 ? this._texture.format : BABYLON2.Engine.TEXTUREFORMAT_RGBA;
},
enumerable: true,
configurable: true
});
BaseTexture2.prototype.readPixels = function(faceIndex, level, buffer) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (level === void 0) {
level = 0;
}
if (buffer === void 0) {
buffer = null;
}
if (!this._texture) {
return null;
}
var size = this.getSize();
var width = size.width;
var height = size.height;
var scene = this.getScene();
if (!scene) {
return null;
}
var engine = scene.getEngine();
if (level != 0) {
width = width / Math.pow(2, level);
height = height / Math.pow(2, level);
width = Math.round(width);
height = Math.round(height);
}
if (this._texture.isCube) {
return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
}
return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
};
BaseTexture2.prototype.releaseInternalTexture = function() {
if (this._texture) {
this._texture.dispose();
this._texture = null;
}
};
Object.defineProperty(BaseTexture2.prototype, "sphericalPolynomial", {
/**
* Get the polynomial representation of the texture data.
* This is mainly use as a fast way to recover IBL Diffuse irradiance data.
* @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
*/
get: function() {
if (!this._texture || !BABYLON2.CubeMapToSphericalPolynomialTools || !this.isReady()) {
return null;
}
if (!this._texture._sphericalPolynomial) {
this._texture._sphericalPolynomial = BABYLON2.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
}
return this._texture._sphericalPolynomial;
},
set: function(value) {
if (this._texture) {
this._texture._sphericalPolynomial = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "_lodTextureHigh", {
/** @hidden */
get: function() {
if (this._texture) {
return this._texture._lodTextureHigh;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "_lodTextureMid", {
/** @hidden */
get: function() {
if (this._texture) {
return this._texture._lodTextureMid;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseTexture2.prototype, "_lodTextureLow", {
/** @hidden */
get: function() {
if (this._texture) {
return this._texture._lodTextureLow;
}
return null;
},
enumerable: true,
configurable: true
});
BaseTexture2.prototype.dispose = function() {
if (!this._scene) {
return;
}
this._scene.stopAnimation(this);
this._scene._removePendingData(this);
var index = this._scene.textures.indexOf(this);
if (index >= 0) {
this._scene.textures.splice(index, 1);
}
this._scene.onTextureRemovedObservable.notifyObservers(this);
if (this._texture === void 0) {
return;
}
this.releaseInternalTexture();
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
};
BaseTexture2.prototype.serialize = function() {
if (!this.name) {
return null;
}
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
BABYLON2.Animation.AppendSerializedAnimations(this, serializationObject);
return serializationObject;
};
BaseTexture2.WhenAllReady = function(textures, callback) {
var numRemaining = textures.length;
if (numRemaining === 0) {
callback();
return;
}
var _loop_1 = function() {
texture = textures[i2];
if (texture.isReady()) {
if (--numRemaining === 0) {
callback();
}
} else {
onLoadObservable = texture.onLoadObservable;
var onLoadCallback_1 = function() {
onLoadObservable.removeCallback(onLoadCallback_1);
if (--numRemaining === 0) {
callback();
}
};
onLoadObservable.add(onLoadCallback_1);
}
};
var texture, onLoadObservable;
for (var i2 = 0; i2 < textures.length; i2++) {
_loop_1();
}
};
BaseTexture2.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "name", void 0);
__decorate([
BABYLON2.serialize("hasAlpha")
], BaseTexture2.prototype, "_hasAlpha", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "getAlphaFromRGB", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "level", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "coordinatesIndex", void 0);
__decorate([
BABYLON2.serialize("coordinatesMode")
], BaseTexture2.prototype, "_coordinatesMode", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "wrapU", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "wrapV", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "wrapR", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "anisotropicFilteringLevel", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "isCube", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "is3D", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "gammaSpace", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "invertZ", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "lodLevelInAlpha", void 0);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "lodGenerationOffset", null);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "lodGenerationScale", null);
__decorate([
BABYLON2.serialize()
], BaseTexture2.prototype, "isRenderTarget", void 0);
return BaseTexture2;
}()
);
BABYLON2.BaseTexture = BaseTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Texture = (
/** @class */
function(_super) {
__extends(Texture2, _super);
function Texture2(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
if (noMipmap === void 0) {
noMipmap = false;
}
if (invertY === void 0) {
invertY = true;
}
if (samplingMode === void 0) {
samplingMode = Texture2.TRILINEAR_SAMPLINGMODE;
}
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (buffer === void 0) {
buffer = null;
}
if (deleteBuffer === void 0) {
deleteBuffer = false;
}
var _this = _super.call(this, scene) || this;
_this.uOffset = 0;
_this.vOffset = 0;
_this.uScale = 1;
_this.vScale = 1;
_this.uAng = 0;
_this.vAng = 0;
_this.wAng = 0;
_this.uRotationCenter = 0.5;
_this.vRotationCenter = 0.5;
_this.wRotationCenter = 0.5;
_this.onLoadObservable = new BABYLON2.Observable();
_this._isBlocking = true;
_this.name = url || "";
_this.url = url;
_this._noMipmap = noMipmap;
_this._invertY = invertY;
_this._samplingMode = samplingMode;
_this._buffer = buffer;
_this._deleteBuffer = deleteBuffer;
if (format) {
_this._format = format;
}
scene = _this.getScene();
if (!scene) {
return _this;
}
scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
var load = function() {
if (_this.onLoadObservable.hasObservers()) {
_this.onLoadObservable.notifyObservers(_this);
}
if (onLoad) {
onLoad();
}
if (!_this.isBlocking && scene) {
scene.resetCachedMaterial();
}
};
if (!_this.url) {
_this._delayedOnLoad = load;
_this._delayedOnError = onError;
return _this;
}
_this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
if (!_this._texture) {
if (!scene.useDelayedTextureLoading) {
_this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, void 0, _this._format);
if (deleteBuffer) {
delete _this._buffer;
}
} else {
_this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED;
_this._delayedOnLoad = load;
_this._delayedOnError = onError;
}
} else {
if (_this._texture.isReady) {
BABYLON2.Tools.SetImmediate(function() {
return load();
});
} else {
_this._texture.onLoadedObservable.add(load);
}
}
return _this;
}
Object.defineProperty(Texture2.prototype, "noMipmap", {
/**
* Are mip maps generated for this texture or not.
*/
get: function() {
return this._noMipmap;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Texture2.prototype, "isBlocking", {
get: function() {
return this._isBlocking;
},
/**
* Is the texture preventing material to render while loading.
* If false, a default texture will be used instead of the loading one during the preparation step.
*/
set: function(value) {
this._isBlocking = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Texture2.prototype, "samplingMode", {
/**
* Get the current sampling mode associated with the texture.
*/
get: function() {
return this._samplingMode;
},
enumerable: true,
configurable: true
});
Texture2.prototype.updateURL = function(url, buffer) {
if (buffer === void 0) {
buffer = null;
}
if (this.url) {
throw new Error("URL is already set");
}
this.url = url;
this._buffer = buffer;
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED;
this.delayLoad();
};
Texture2.prototype.delayLoad = function() {
if (this.delayLoadState !== BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED) {
return;
}
var scene = this.getScene();
if (!scene) {
return;
}
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADED;
this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
if (!this._texture) {
this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
if (this._deleteBuffer) {
delete this._buffer;
}
} else {
if (this._delayedOnLoad) {
if (this._texture.isReady) {
BABYLON2.Tools.SetImmediate(this._delayedOnLoad);
} else {
this._texture.onLoadedObservable.add(this._delayedOnLoad);
}
}
}
this._delayedOnLoad = null;
this._delayedOnError = null;
};
Texture2.prototype.updateSamplingMode = function(samplingMode) {
if (!this._texture) {
return;
}
var scene = this.getScene();
if (!scene) {
return;
}
this._samplingMode = samplingMode;
scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
};
Texture2.prototype._prepareRowForTextureGeneration = function(x, y, z, t) {
x *= this.uScale;
y *= this.vScale;
x -= this.uRotationCenter * this.uScale;
y -= this.vRotationCenter * this.vScale;
z -= this.wRotationCenter;
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
t.x += this.uRotationCenter * this.uScale + this.uOffset;
t.y += this.vRotationCenter * this.vScale + this.vOffset;
t.z += this.wRotationCenter;
};
Texture2.prototype.getTextureMatrix = function() {
var _this = this;
if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
return this._cachedTextureMatrix;
}
this._cachedUOffset = this.uOffset;
this._cachedVOffset = this.vOffset;
this._cachedUScale = this.uScale;
this._cachedVScale = this.vScale;
this._cachedUAng = this.uAng;
this._cachedVAng = this.vAng;
this._cachedWAng = this.wAng;
if (!this._cachedTextureMatrix) {
this._cachedTextureMatrix = BABYLON2.Matrix.Zero();
this._rowGenerationMatrix = new BABYLON2.Matrix();
this._t0 = BABYLON2.Vector3.Zero();
this._t1 = BABYLON2.Vector3.Zero();
this._t2 = BABYLON2.Vector3.Zero();
}
BABYLON2.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
this._prepareRowForTextureGeneration(1, 0, 0, this._t1);
this._prepareRowForTextureGeneration(0, 1, 0, this._t2);
this._t1.subtractInPlace(this._t0);
this._t2.subtractInPlace(this._t0);
BABYLON2.Matrix.IdentityToRef(this._cachedTextureMatrix);
this._cachedTextureMatrix.m[0] = this._t1.x;
this._cachedTextureMatrix.m[1] = this._t1.y;
this._cachedTextureMatrix.m[2] = this._t1.z;
this._cachedTextureMatrix.m[4] = this._t2.x;
this._cachedTextureMatrix.m[5] = this._t2.y;
this._cachedTextureMatrix.m[6] = this._t2.z;
this._cachedTextureMatrix.m[8] = this._t0.x;
this._cachedTextureMatrix.m[9] = this._t0.y;
this._cachedTextureMatrix.m[10] = this._t0.z;
var scene = this.getScene();
if (!scene) {
return this._cachedTextureMatrix;
}
scene.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag, function(mat) {
return mat.hasTexture(_this);
});
return this._cachedTextureMatrix;
};
Texture2.prototype.getReflectionTextureMatrix = function() {
var _this = this;
var scene = this.getScene();
if (!scene) {
return this._cachedTextureMatrix;
}
if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
if (this.coordinatesMode === Texture2.PROJECTION_MODE) {
if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
return this._cachedTextureMatrix;
}
} else {
return this._cachedTextureMatrix;
}
}
if (!this._cachedTextureMatrix) {
this._cachedTextureMatrix = BABYLON2.Matrix.Zero();
}
if (!this._projectionModeMatrix) {
this._projectionModeMatrix = BABYLON2.Matrix.Zero();
}
this._cachedUOffset = this.uOffset;
this._cachedVOffset = this.vOffset;
this._cachedUScale = this.uScale;
this._cachedVScale = this.vScale;
this._cachedCoordinatesMode = this.coordinatesMode;
switch (this.coordinatesMode) {
case Texture2.PLANAR_MODE:
BABYLON2.Matrix.IdentityToRef(this._cachedTextureMatrix);
this._cachedTextureMatrix[0] = this.uScale;
this._cachedTextureMatrix[5] = this.vScale;
this._cachedTextureMatrix[12] = this.uOffset;
this._cachedTextureMatrix[13] = this.vOffset;
break;
case Texture2.PROJECTION_MODE:
BABYLON2.Matrix.IdentityToRef(this._projectionModeMatrix);
this._projectionModeMatrix.m[0] = 0.5;
this._projectionModeMatrix.m[5] = -0.5;
this._projectionModeMatrix.m[10] = 0;
this._projectionModeMatrix.m[12] = 0.5;
this._projectionModeMatrix.m[13] = 0.5;
this._projectionModeMatrix.m[14] = 1;
this._projectionModeMatrix.m[15] = 1;
var projectionMatrix = scene.getProjectionMatrix();
this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
break;
default:
BABYLON2.Matrix.IdentityToRef(this._cachedTextureMatrix);
break;
}
scene.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag, function(mat) {
return mat.getActiveTextures().indexOf(_this) !== -1;
});
return this._cachedTextureMatrix;
};
Texture2.prototype.clone = function() {
var _this = this;
return BABYLON2.SerializationHelper.Clone(function() {
return new Texture2(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
}, this);
};
Texture2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
serializationObject.base64String = this._buffer;
serializationObject.name = serializationObject.name.replace("data:", "");
}
serializationObject.invertY = this._invertY;
serializationObject.samplingMode = this.samplingMode;
return serializationObject;
};
Texture2.prototype.getClassName = function() {
return "Texture";
};
Texture2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
this.onLoadObservable.clear();
this._delayedOnLoad = null;
this._delayedOnError = null;
};
Texture2.Parse = function(parsedTexture, scene, rootUrl) {
if (parsedTexture.customType) {
var customTexture = BABYLON2.Tools.Instantiate(parsedTexture.customType);
var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
}
}
return parsedCustomTexture;
}
if (parsedTexture.isCube) {
return BABYLON2.CubeTexture.Parse(parsedTexture, scene, rootUrl);
}
if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
return null;
}
var texture = BABYLON2.SerializationHelper.Parse(function() {
var generateMipMaps = true;
if (parsedTexture.noMipmap) {
generateMipMaps = false;
}
if (parsedTexture.mirrorPlane) {
var mirrorTexture = new BABYLON2.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
mirrorTexture._waitingRenderList = parsedTexture.renderList;
mirrorTexture.mirrorPlane = BABYLON2.Plane.FromArray(parsedTexture.mirrorPlane);
return mirrorTexture;
} else if (parsedTexture.isRenderTarget) {
var renderTargetTexture = new BABYLON2.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
renderTargetTexture._waitingRenderList = parsedTexture.renderList;
return renderTargetTexture;
} else {
var texture2;
if (parsedTexture.base64String) {
texture2 = Texture2.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
} else {
var url = rootUrl + parsedTexture.name;
if (Texture2.UseSerializedUrlIfAny && parsedTexture.url) {
url = parsedTexture.url;
}
texture2 = new Texture2(url, scene, !generateMipMaps, parsedTexture.invertY);
}
return texture2;
}
}, parsedTexture, scene);
if (parsedTexture.samplingMode) {
var sampling = parsedTexture.samplingMode;
if (texture._samplingMode !== sampling) {
texture.updateSamplingMode(sampling);
}
}
if (parsedTexture.animations) {
for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
var parsedAnimation = parsedTexture.animations[animationIndex];
texture.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
}
return texture;
};
Texture2.CreateFromBase64String = function(data2, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
if (samplingMode === void 0) {
samplingMode = Texture2.TRILINEAR_SAMPLINGMODE;
}
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (format === void 0) {
format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
}
return new Texture2("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data2, false, format);
};
Texture2.LoadFromDataString = function(name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
if (deleteBuffer === void 0) {
deleteBuffer = false;
}
if (noMipmap === void 0) {
noMipmap = false;
}
if (invertY === void 0) {
invertY = true;
}
if (samplingMode === void 0) {
samplingMode = Texture2.TRILINEAR_SAMPLINGMODE;
}
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (format === void 0) {
format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
}
if (name.substr(0, 5) !== "data:") {
name = "data:" + name;
}
return new Texture2(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
};
Texture2.NEAREST_SAMPLINGMODE = BABYLON2.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
Texture2.NEAREST_NEAREST_MIPLINEAR = BABYLON2.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;
Texture2.BILINEAR_SAMPLINGMODE = BABYLON2.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
Texture2.LINEAR_LINEAR_MIPNEAREST = BABYLON2.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;
Texture2.TRILINEAR_SAMPLINGMODE = BABYLON2.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
Texture2.LINEAR_LINEAR_MIPLINEAR = BABYLON2.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;
Texture2.NEAREST_NEAREST_MIPNEAREST = BABYLON2.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
Texture2.NEAREST_LINEAR_MIPNEAREST = BABYLON2.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
Texture2.NEAREST_LINEAR_MIPLINEAR = BABYLON2.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
Texture2.NEAREST_LINEAR = BABYLON2.Engine.TEXTURE_NEAREST_LINEAR;
Texture2.NEAREST_NEAREST = BABYLON2.Engine.TEXTURE_NEAREST_NEAREST;
Texture2.LINEAR_NEAREST_MIPNEAREST = BABYLON2.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
Texture2.LINEAR_NEAREST_MIPLINEAR = BABYLON2.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
Texture2.LINEAR_LINEAR = BABYLON2.Engine.TEXTURE_LINEAR_LINEAR;
Texture2.LINEAR_NEAREST = BABYLON2.Engine.TEXTURE_LINEAR_NEAREST;
Texture2.EXPLICIT_MODE = BABYLON2.Engine.TEXTURE_EXPLICIT_MODE;
Texture2.SPHERICAL_MODE = BABYLON2.Engine.TEXTURE_SPHERICAL_MODE;
Texture2.PLANAR_MODE = BABYLON2.Engine.TEXTURE_PLANAR_MODE;
Texture2.CUBIC_MODE = BABYLON2.Engine.TEXTURE_CUBIC_MODE;
Texture2.PROJECTION_MODE = BABYLON2.Engine.TEXTURE_PROJECTION_MODE;
Texture2.SKYBOX_MODE = BABYLON2.Engine.TEXTURE_SKYBOX_MODE;
Texture2.INVCUBIC_MODE = BABYLON2.Engine.TEXTURE_INVCUBIC_MODE;
Texture2.EQUIRECTANGULAR_MODE = BABYLON2.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
Texture2.FIXED_EQUIRECTANGULAR_MODE = BABYLON2.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
Texture2.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON2.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
Texture2.CLAMP_ADDRESSMODE = BABYLON2.Engine.TEXTURE_CLAMP_ADDRESSMODE;
Texture2.WRAP_ADDRESSMODE = BABYLON2.Engine.TEXTURE_WRAP_ADDRESSMODE;
Texture2.MIRROR_ADDRESSMODE = BABYLON2.Engine.TEXTURE_MIRROR_ADDRESSMODE;
Texture2.UseSerializedUrlIfAny = false;
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "url", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "uOffset", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "vOffset", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "uScale", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "vScale", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "uAng", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "vAng", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "wAng", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "uRotationCenter", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "vRotationCenter", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "wRotationCenter", void 0);
__decorate([
BABYLON2.serialize()
], Texture2.prototype, "isBlocking", null);
return Texture2;
}(BABYLON2.BaseTexture)
);
BABYLON2.Texture = Texture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _CreationDataStorage = (
/** @class */
function() {
function _CreationDataStorage2() {
}
return _CreationDataStorage2;
}()
);
BABYLON2._CreationDataStorage = _CreationDataStorage;
var _InstanceDataStorage = (
/** @class */
function() {
function _InstanceDataStorage2() {
this.visibleInstances = {};
this.renderIdForInstances = new Array();
this.batchCache = new _InstancesBatch();
this.instancesBufferSize = 32 * 16 * 4;
}
return _InstanceDataStorage2;
}()
);
var _InstancesBatch = (
/** @class */
function() {
function _InstancesBatch2() {
this.mustReturn = false;
this.visibleInstances = new Array();
this.renderSelf = new Array();
}
return _InstancesBatch2;
}()
);
BABYLON2._InstancesBatch = _InstancesBatch;
var Mesh = (
/** @class */
function(_super) {
__extends(Mesh2, _super);
function Mesh2(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
if (scene === void 0) {
scene = null;
}
if (parent === void 0) {
parent = null;
}
if (source === void 0) {
source = null;
}
if (clonePhysicsImpostor === void 0) {
clonePhysicsImpostor = true;
}
var _this = _super.call(this, name, scene) || this;
_this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NONE;
_this.instances = new Array();
_this._LODLevels = new Array();
_this._instanceDataStorage = new _InstanceDataStorage();
_this._originalBuilderSideOrientation = Mesh2.DEFAULTSIDE;
_this.overrideMaterialSideOrientation = null;
_this._areNormalsFrozen = false;
_this._source = null;
scene = _this.getScene();
if (source) {
if (source._geometry) {
source._geometry.applyToMesh(_this);
}
BABYLON2.Tools.DeepCopy(source, _this, [
"name",
"material",
"skeleton",
"instances",
"parent",
"uniqueId",
"source",
"metadata",
"hasLODLevels",
"geometry",
"isBlocked",
"areNormalsFrozen",
"onBeforeDrawObservable",
"onBeforeRenderObservable",
"onAfterRenderObservable",
"onBeforeDraw"
], ["_poseMatrix"]);
_this._source = source;
_this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
_this._creationDataStorage = source._creationDataStorage;
if (_this._source._ranges) {
var ranges = _this._source._ranges;
for (var name in ranges) {
if (!ranges.hasOwnProperty(name)) {
continue;
}
if (!ranges[name]) {
continue;
}
_this.createAnimationRange(name, ranges[name].from, ranges[name].to);
}
}
if (source.metadata && source.metadata.clone) {
_this.metadata = source.metadata.clone();
} else {
_this.metadata = source.metadata;
}
if (BABYLON2.Tags && BABYLON2.Tags.HasTags(source)) {
BABYLON2.Tags.AddTagsTo(_this, BABYLON2.Tags.GetTags(source, true));
}
_this.parent = source.parent;
_this.setPivotMatrix(source.getPivotMatrix());
_this.id = name + "." + source.id;
_this.material = source.material;
var index;
if (!doNotCloneChildren) {
var directDescendants = source.getDescendants(true);
for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
var child = directDescendants[index_1];
if (child.clone) {
child.clone(name + "." + child.name, _this);
}
}
}
var physicsEngine = _this.getScene().getPhysicsEngine();
if (clonePhysicsImpostor && physicsEngine) {
var impostor = physicsEngine.getImpostorForPhysicsObject(source);
if (impostor) {
_this.physicsImpostor = impostor.clone(_this);
}
}
for (index = 0; index < scene.particleSystems.length; index++) {
var system = scene.particleSystems[index];
if (system.emitter === source) {
system.clone(system.name, _this);
}
}
_this.refreshBoundingInfo();
_this.computeWorldMatrix(true);
}
if (parent !== null) {
_this.parent = parent;
}
return _this;
}
Object.defineProperty(Mesh2.prototype, "onBeforeRenderObservable", {
/**
* An event triggered before rendering the mesh
*/
get: function() {
if (!this._onBeforeRenderObservable) {
this._onBeforeRenderObservable = new BABYLON2.Observable();
}
return this._onBeforeRenderObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh2.prototype, "onAfterRenderObservable", {
/**
* An event triggered after rendering the mesh
*/
get: function() {
if (!this._onAfterRenderObservable) {
this._onAfterRenderObservable = new BABYLON2.Observable();
}
return this._onAfterRenderObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh2.prototype, "onBeforeDrawObservable", {
/**
* An event triggered before drawing the mesh
*/
get: function() {
if (!this._onBeforeDrawObservable) {
this._onBeforeDrawObservable = new BABYLON2.Observable();
}
return this._onBeforeDrawObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh2.prototype, "onBeforeDraw", {
/**
* Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
*/
set: function(callback) {
if (this._onBeforeDrawObserver) {
this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
}
this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh2.prototype, "morphTargetManager", {
/**
* Gets or sets the morph target manager
* @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
*/
get: function() {
return this._morphTargetManager;
},
set: function(value) {
if (this._morphTargetManager === value) {
return;
}
this._morphTargetManager = value;
this._syncGeometryWithMorphTargetManager();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh2.prototype, "source", {
/**
* Gets the source mesh (the one used to clone this one from)
*/
get: function() {
return this._source;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Mesh2.prototype, "isUnIndexed", {
/**
* Gets or sets a boolean indicating that this mesh does not use index buffer
*/
get: function() {
return this._unIndexed;
},
set: function(value) {
if (this._unIndexed !== value) {
this._unIndexed = value;
this._markSubMeshesAsAttributesDirty();
}
},
enumerable: true,
configurable: true
});
Mesh2.prototype.getClassName = function() {
return "Mesh";
};
Mesh2.prototype.toString = function(fullDetails) {
var ret = _super.prototype.toString.call(this, fullDetails);
ret += ", n vertices: " + this.getTotalVertices();
ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE");
if (this.animations) {
for (var i2 = 0; i2 < this.animations.length; i2++) {
ret += ", animation[0]: " + this.animations[i2].toString(fullDetails);
}
}
if (fullDetails) {
if (this._geometry) {
var ib = this.getIndices();
var vb = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (vb && ib) {
ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
}
} else {
ret += ", flat shading: UNKNOWN";
}
}
return ret;
};
Mesh2.prototype._unBindEffect = function() {
_super.prototype._unBindEffect.call(this);
for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
var instance = _a[_i];
instance._unBindEffect();
}
};
Object.defineProperty(Mesh2.prototype, "hasLODLevels", {
/**
* Gets a boolean indicating if this mesh has LOD
*/
get: function() {
return this._LODLevels.length > 0;
},
enumerable: true,
configurable: true
});
Mesh2.prototype.getLODLevels = function() {
return this._LODLevels;
};
Mesh2.prototype._sortLODLevels = function() {
this._LODLevels.sort(function(a, b2) {
if (a.distance < b2.distance) {
return 1;
}
if (a.distance > b2.distance) {
return -1;
}
return 0;
});
};
Mesh2.prototype.addLODLevel = function(distance, mesh2) {
if (mesh2 && mesh2._masterMesh) {
BABYLON2.Tools.Warn("You cannot use a mesh as LOD level twice");
return this;
}
var level = new BABYLON2.MeshLODLevel(distance, mesh2);
this._LODLevels.push(level);
if (mesh2) {
mesh2._masterMesh = this;
}
this._sortLODLevels();
return this;
};
Mesh2.prototype.getLODLevelAtDistance = function(distance) {
for (var index = 0; index < this._LODLevels.length; index++) {
var level = this._LODLevels[index];
if (level.distance === distance) {
return level.mesh;
}
}
return null;
};
Mesh2.prototype.removeLODLevel = function(mesh2) {
for (var index = 0; index < this._LODLevels.length; index++) {
if (this._LODLevels[index].mesh === mesh2) {
this._LODLevels.splice(index, 1);
if (mesh2) {
mesh2._masterMesh = null;
}
}
}
this._sortLODLevels();
return this;
};
Mesh2.prototype.getLOD = function(camera2, boundingSphere) {
if (!this._LODLevels || this._LODLevels.length === 0) {
return this;
}
var bSphere;
if (boundingSphere) {
bSphere = boundingSphere;
} else {
var boundingInfo = this.getBoundingInfo();
bSphere = boundingInfo.boundingSphere;
}
var distanceToCamera = bSphere.centerWorld.subtract(camera2.globalPosition).length();
if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
if (this.onLODLevelSelection) {
this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
}
return this;
}
for (var index = 0; index < this._LODLevels.length; index++) {
var level = this._LODLevels[index];
if (level.distance < distanceToCamera) {
if (level.mesh) {
level.mesh._preActivate();
level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
}
if (this.onLODLevelSelection) {
this.onLODLevelSelection(distanceToCamera, this, level.mesh);
}
return level.mesh;
}
}
if (this.onLODLevelSelection) {
this.onLODLevelSelection(distanceToCamera, this, this);
}
return this;
};
Object.defineProperty(Mesh2.prototype, "geometry", {
/**
* Gets the mesh internal Geometry object
*/
get: function() {
return this._geometry;
},
enumerable: true,
configurable: true
});
Mesh2.prototype.getTotalVertices = function() {
if (this._geometry === null || this._geometry === void 0) {
return 0;
}
return this._geometry.getTotalVertices();
};
Mesh2.prototype.getVerticesData = function(kind, copyWhenShared, forceCopy) {
if (!this._geometry) {
return null;
}
return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
};
Mesh2.prototype.getVertexBuffer = function(kind) {
if (!this._geometry) {
return null;
}
return this._geometry.getVertexBuffer(kind);
};
Mesh2.prototype.isVerticesDataPresent = function(kind) {
if (!this._geometry) {
if (this._delayInfo) {
return this._delayInfo.indexOf(kind) !== -1;
}
return false;
}
return this._geometry.isVerticesDataPresent(kind);
};
Mesh2.prototype.isVertexBufferUpdatable = function(kind) {
if (!this._geometry) {
if (this._delayInfo) {
return this._delayInfo.indexOf(kind) !== -1;
}
return false;
}
return this._geometry.isVertexBufferUpdatable(kind);
};
Mesh2.prototype.getVerticesDataKinds = function() {
if (!this._geometry) {
var result = new Array();
if (this._delayInfo) {
this._delayInfo.forEach(function(kind, index, array) {
result.push(kind);
});
}
return result;
}
return this._geometry.getVerticesDataKinds();
};
Mesh2.prototype.getTotalIndices = function() {
if (!this._geometry) {
return 0;
}
return this._geometry.getTotalIndices();
};
Mesh2.prototype.getIndices = function(copyWhenShared, forceCopy) {
if (!this._geometry) {
return [];
}
return this._geometry.getIndices(copyWhenShared, forceCopy);
};
Object.defineProperty(Mesh2.prototype, "isBlocked", {
get: function() {
return this._masterMesh !== null && this._masterMesh !== void 0;
},
enumerable: true,
configurable: true
});
Mesh2.prototype.isReady = function(completeCheck, forceInstanceSupport) {
if (completeCheck === void 0) {
completeCheck = false;
}
if (forceInstanceSupport === void 0) {
forceInstanceSupport = false;
}
if (this.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_LOADING) {
return false;
}
if (!_super.prototype.isReady.call(this, completeCheck)) {
return false;
}
if (!this.subMeshes || this.subMeshes.length === 0) {
return true;
}
if (!completeCheck) {
return true;
}
var engine = this.getEngine();
var scene = this.getScene();
var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
this.computeWorldMatrix();
var mat = this.material || scene.defaultMaterial;
if (mat) {
if (mat.storeEffectOnSubMeshes) {
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
var effectiveMaterial = subMesh.getMaterial();
if (effectiveMaterial) {
if (effectiveMaterial.storeEffectOnSubMeshes) {
if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
return false;
}
} else {
if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
return false;
}
}
}
}
} else {
if (!mat.isReady(this, hardwareInstancedRendering)) {
return false;
}
}
}
for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
var light = _c[_b];
var generator = light.getShadowGenerator();
if (generator) {
for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
var subMesh = _e[_d];
if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
return false;
}
}
}
}
for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
var lod = _g[_f];
if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
return false;
}
}
return true;
};
Object.defineProperty(Mesh2.prototype, "areNormalsFrozen", {
/**
* Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
*/
get: function() {
return this._areNormalsFrozen;
},
enumerable: true,
configurable: true
});
Mesh2.prototype.freezeNormals = function() {
this._areNormalsFrozen = true;
return this;
};
Mesh2.prototype.unfreezeNormals = function() {
this._areNormalsFrozen = false;
return this;
};
Object.defineProperty(Mesh2.prototype, "overridenInstanceCount", {
/**
* Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
*/
set: function(count) {
this._instanceDataStorage.overridenInstanceCount = count;
},
enumerable: true,
configurable: true
});
Mesh2.prototype._preActivate = function() {
var sceneRenderId = this.getScene().getRenderId();
if (this._preActivateId === sceneRenderId) {
return this;
}
this._preActivateId = sceneRenderId;
this._instanceDataStorage.visibleInstances = null;
return this;
};
Mesh2.prototype._preActivateForIntermediateRendering = function(renderId) {
if (this._instanceDataStorage.visibleInstances) {
this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
}
return this;
};
Mesh2.prototype._registerInstanceForRenderId = function(instance, renderId) {
if (!this._instanceDataStorage.visibleInstances) {
this._instanceDataStorage.visibleInstances = {};
this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
}
if (!this._instanceDataStorage.visibleInstances[renderId]) {
this._instanceDataStorage.visibleInstances[renderId] = new Array();
}
this._instanceDataStorage.visibleInstances[renderId].push(instance);
return this;
};
Mesh2.prototype.refreshBoundingInfo = function() {
return this._refreshBoundingInfo(false);
};
Mesh2.prototype._refreshBoundingInfo = function(applySkeleton) {
if (this._boundingInfo && this._boundingInfo.isLocked) {
return this;
}
var data2 = this._getPositionData(applySkeleton);
if (data2) {
var bias = this.geometry ? this.geometry.boundingBias : null;
var extend = BABYLON2.Tools.ExtractMinAndMax(data2, 0, this.getTotalVertices(), bias);
this._boundingInfo = new BABYLON2.BoundingInfo(extend.minimum, extend.maximum);
}
if (this.subMeshes) {
for (var index = 0; index < this.subMeshes.length; index++) {
this.subMeshes[index].refreshBoundingInfo();
}
}
this._updateBoundingInfo();
return this;
};
Mesh2.prototype._getPositionData = function(applySkeleton) {
var data2 = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (data2 && applySkeleton && this.skeleton) {
data2 = BABYLON2.Tools.Slice(data2);
var matricesIndicesData = this.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind);
var matricesWeightsData = this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (matricesWeightsData && matricesIndicesData) {
var needExtras = this.numBoneInfluencers > 4;
var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind) : null;
var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind) : null;
var skeletonMatrices = this.skeleton.getTransformMatrices(this);
var tempVector = BABYLON2.Tmp.Vector3[0];
var finalMatrix = BABYLON2.Tmp.Matrix[0];
var tempMatrix = BABYLON2.Tmp.Matrix[1];
var matWeightIdx = 0;
for (var index = 0; index < data2.length; index += 3, matWeightIdx += 4) {
finalMatrix.reset();
var inf;
var weight;
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsData[matWeightIdx + inf];
if (weight > 0) {
BABYLON2.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
}
if (needExtras) {
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsExtraData[matWeightIdx + inf];
if (weight > 0) {
BABYLON2.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
}
}
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(data2[index], data2[index + 1], data2[index + 2], finalMatrix, tempVector);
tempVector.toArray(data2, index);
}
}
}
return data2;
};
Mesh2.prototype._createGlobalSubMesh = function(force) {
var totalVertices = this.getTotalVertices();
if (!totalVertices || !this.getIndices()) {
return null;
}
if (this.subMeshes && this.subMeshes.length > 0) {
var ib = this.getIndices();
if (!ib) {
return null;
}
var totalIndices = ib.length;
var needToRecreate = false;
if (force) {
needToRecreate = true;
} else {
for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
var submesh = _a[_i];
if (submesh.indexStart + submesh.indexCount >= totalIndices) {
needToRecreate = true;
break;
}
if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
needToRecreate = true;
break;
}
}
}
if (!needToRecreate) {
return this.subMeshes[0];
}
}
this.releaseSubMeshes();
return new BABYLON2.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
};
Mesh2.prototype.subdivide = function(count) {
if (count < 1) {
return;
}
var totalIndices = this.getTotalIndices();
var subdivisionSize = totalIndices / count | 0;
var offset = 0;
while (subdivisionSize % 3 !== 0) {
subdivisionSize++;
}
this.releaseSubMeshes();
for (var index = 0; index < count; index++) {
if (offset >= totalIndices) {
break;
}
BABYLON2.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
offset += subdivisionSize;
}
this.synchronizeInstances();
};
Mesh2.prototype.setVerticesData = function(kind, data2, updatable, stride) {
if (updatable === void 0) {
updatable = false;
}
if (!this._geometry) {
var vertexData = new BABYLON2.VertexData();
vertexData.set(data2, kind);
var scene = this.getScene();
new BABYLON2.Geometry(BABYLON2.Geometry.RandomId(), scene, vertexData, updatable, this);
} else {
this._geometry.setVerticesData(kind, data2, updatable, stride);
}
return this;
};
Mesh2.prototype.markVerticesDataAsUpdatable = function(kind, updatable) {
if (updatable === void 0) {
updatable = true;
}
var vb = this.getVertexBuffer(kind);
if (!vb || vb.isUpdatable() === updatable) {
return;
}
this.setVerticesData(kind, this.getVerticesData(kind), updatable);
};
Mesh2.prototype.setVerticesBuffer = function(buffer) {
if (!this._geometry) {
this._geometry = BABYLON2.Geometry.CreateGeometryForMesh(this);
}
this._geometry.setVerticesBuffer(buffer);
return this;
};
Mesh2.prototype.updateVerticesData = function(kind, data2, updateExtends, makeItUnique) {
if (!this._geometry) {
return this;
}
if (!makeItUnique) {
this._geometry.updateVerticesData(kind, data2, updateExtends);
} else {
this.makeGeometryUnique();
this.updateVerticesData(kind, data2, updateExtends, false);
}
return this;
};
Mesh2.prototype.updateMeshPositions = function(positionFunction, computeNormals) {
if (computeNormals === void 0) {
computeNormals = true;
}
var positions = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (!positions) {
return this;
}
positionFunction(positions);
this.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, positions, false, false);
if (computeNormals) {
var indices = this.getIndices();
var normals = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
if (!normals) {
return this;
}
BABYLON2.VertexData.ComputeNormals(positions, indices, normals);
this.updateVerticesData(BABYLON2.VertexBuffer.NormalKind, normals, false, false);
}
return this;
};
Mesh2.prototype.makeGeometryUnique = function() {
if (!this._geometry) {
return this;
}
var oldGeometry = this._geometry;
var geometry = this._geometry.copy(BABYLON2.Geometry.RandomId());
oldGeometry.releaseForMesh(this, true);
geometry.applyToMesh(this);
return this;
};
Mesh2.prototype.setIndices = function(indices, totalVertices, updatable) {
if (totalVertices === void 0) {
totalVertices = null;
}
if (updatable === void 0) {
updatable = false;
}
if (!this._geometry) {
var vertexData = new BABYLON2.VertexData();
vertexData.indices = indices;
var scene = this.getScene();
new BABYLON2.Geometry(BABYLON2.Geometry.RandomId(), scene, vertexData, updatable, this);
} else {
this._geometry.setIndices(indices, totalVertices, updatable);
}
return this;
};
Mesh2.prototype.updateIndices = function(indices, offset) {
if (!this._geometry) {
return this;
}
this._geometry.updateIndices(indices, offset);
return this;
};
Mesh2.prototype.toLeftHanded = function() {
if (!this._geometry) {
return this;
}
this._geometry.toLeftHanded();
return this;
};
Mesh2.prototype._bind = function(subMesh, effect, fillMode) {
if (!this._geometry) {
return this;
}
var engine = this.getScene().getEngine();
var indexToBind;
if (this._unIndexed) {
indexToBind = null;
} else {
switch (fillMode) {
case BABYLON2.Material.PointFillMode:
indexToBind = null;
break;
case BABYLON2.Material.WireFrameFillMode:
indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
break;
default:
case BABYLON2.Material.TriangleFillMode:
indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
break;
}
}
this._geometry._bind(effect, indexToBind);
return this;
};
Mesh2.prototype._draw = function(subMesh, fillMode, instancesCount, alternate) {
if (alternate === void 0) {
alternate = false;
}
if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) {
return this;
}
if (this._onBeforeDrawObservable) {
this._onBeforeDrawObservable.notifyObservers(this);
}
var scene = this.getScene();
var engine = scene.getEngine();
if (this._unIndexed || fillMode == BABYLON2.Material.PointFillMode) {
engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
} else if (fillMode == BABYLON2.Material.WireFrameFillMode) {
engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
} else {
engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
}
if (scene._isAlternateRenderingEnabled && !alternate) {
var effect = subMesh.effect || this._effectiveMaterial.getEffect();
if (!effect || !scene.activeCamera) {
return this;
}
scene._switchToAlternateCameraConfiguration(true);
this._effectiveMaterial.bindView(effect);
this._effectiveMaterial.bindViewProjection(effect);
engine.setViewport(scene.activeCamera._alternateCamera.viewport);
this._draw(subMesh, fillMode, instancesCount, true);
engine.setViewport(scene.activeCamera.viewport);
scene._switchToAlternateCameraConfiguration(false);
this._effectiveMaterial.bindView(effect);
this._effectiveMaterial.bindViewProjection(effect);
}
return this;
};
Mesh2.prototype.registerBeforeRender = function(func) {
this.onBeforeRenderObservable.add(func);
return this;
};
Mesh2.prototype.unregisterBeforeRender = function(func) {
this.onBeforeRenderObservable.removeCallback(func);
return this;
};
Mesh2.prototype.registerAfterRender = function(func) {
this.onAfterRenderObservable.add(func);
return this;
};
Mesh2.prototype.unregisterAfterRender = function(func) {
this.onAfterRenderObservable.removeCallback(func);
return this;
};
Mesh2.prototype._getInstancesRenderList = function(subMeshId) {
var scene = this.getScene();
var batchCache = this._instanceDataStorage.batchCache;
batchCache.mustReturn = false;
batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
batchCache.visibleInstances[subMeshId] = null;
if (this._instanceDataStorage.visibleInstances) {
var visibleInstances = this._instanceDataStorage.visibleInstances;
var currentRenderId = scene.getRenderId();
var defaultRenderId = scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId;
batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
var selfRenderId = this._renderId;
if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
currentRenderId = Math.max(defaultRenderId, currentRenderId);
selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
}
var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
batchCache.mustReturn = true;
return batchCache;
}
if (currentRenderId !== selfRenderId) {
batchCache.renderSelf[subMeshId] = false;
}
}
this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
}
return batchCache;
};
Mesh2.prototype._renderWithInstances = function(subMesh, fillMode, batch, effect, engine) {
var visibleInstances = batch.visibleInstances[subMesh._id];
if (!visibleInstances) {
return this;
}
var matricesCount = visibleInstances.length + 1;
var bufferSize = matricesCount * 16 * 4;
var instanceStorage = this._instanceDataStorage;
var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
var instancesBuffer = instanceStorage.instancesBuffer;
while (instanceStorage.instancesBufferSize < bufferSize) {
instanceStorage.instancesBufferSize *= 2;
}
if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
}
var offset = 0;
var instancesCount = 0;
var world = this.getWorldMatrix();
if (batch.renderSelf[subMesh._id]) {
world.copyToArray(instanceStorage.instancesData, offset);
offset += 16;
instancesCount++;
}
if (visibleInstances) {
for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
var instance = visibleInstances[instanceIndex];
instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
offset += 16;
instancesCount++;
}
}
if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
if (instancesBuffer) {
instancesBuffer.dispose();
}
instancesBuffer = new BABYLON2.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
instanceStorage.instancesBuffer = instancesBuffer;
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
} else {
instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
}
this._bind(subMesh, effect, fillMode);
this._draw(subMesh, fillMode, instancesCount);
engine.unbindInstanceAttributes();
return this;
};
Mesh2.prototype._processRendering = function(subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
var scene = this.getScene();
var engine = scene.getEngine();
if (hardwareInstancedRendering) {
this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
} else {
if (batch.renderSelf[subMesh._id]) {
if (onBeforeDraw) {
onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
}
this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
}
var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
if (visibleInstancesForSubMesh) {
for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
var instance = visibleInstancesForSubMesh[instanceIndex];
var world = instance.getWorldMatrix();
if (onBeforeDraw) {
onBeforeDraw(true, world, effectiveMaterial);
}
this._draw(subMesh, fillMode);
}
}
}
return this;
};
Mesh2.prototype.render = function(subMesh, enableAlphaMode) {
if (this._checkOcclusionQuery()) {
return this;
}
var scene = this.getScene();
var batch = this._getInstancesRenderList(subMesh._id);
if (batch.mustReturn) {
return this;
}
if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) {
return this;
}
if (this._onBeforeRenderObservable) {
this._onBeforeRenderObservable.notifyObservers(this);
}
var engine = scene.getEngine();
var hardwareInstancedRendering = engine.getCaps().instancedArrays && batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0;
var material = subMesh.getMaterial();
if (!material) {
return this;
}
this._effectiveMaterial = material;
if (this._effectiveMaterial.storeEffectOnSubMeshes) {
if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
return this;
}
} else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
return this;
}
if (enableAlphaMode) {
engine.setAlphaMode(this._effectiveMaterial.alphaMode);
}
for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
var step = _a[_i];
step.action(this, subMesh, batch);
}
var effect;
if (this._effectiveMaterial.storeEffectOnSubMeshes) {
effect = subMesh.effect;
} else {
effect = this._effectiveMaterial.getEffect();
}
if (!effect) {
return this;
}
var sideOrientation = this.overrideMaterialSideOrientation;
if (sideOrientation == null) {
sideOrientation = this._effectiveMaterial.sideOrientation;
if (this._getWorldMatrixDeterminant() < 0) {
sideOrientation = sideOrientation === BABYLON2.Material.ClockWiseSideOrientation ? BABYLON2.Material.CounterClockWiseSideOrientation : BABYLON2.Material.ClockWiseSideOrientation;
}
}
var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
if (this._effectiveMaterial.forceDepthWrite) {
engine.setDepthWrite(true);
}
var fillMode = scene.forcePointsCloud ? BABYLON2.Material.PointFillMode : scene.forceWireframe ? BABYLON2.Material.WireFrameFillMode : this._effectiveMaterial.fillMode;
if (!hardwareInstancedRendering) {
this._bind(subMesh, effect, fillMode);
}
var world = this.getWorldMatrix();
if (this._effectiveMaterial.storeEffectOnSubMeshes) {
this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
} else {
this._effectiveMaterial.bind(world, this);
}
if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
}
this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
this._effectiveMaterial.unbind();
for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
var step = _c[_b];
step.action(this, subMesh, batch);
}
if (this._onAfterRenderObservable) {
this._onAfterRenderObservable.notifyObservers(this);
}
return this;
};
Mesh2.prototype._onBeforeDraw = function(isInstance, world, effectiveMaterial) {
if (isInstance && effectiveMaterial) {
effectiveMaterial.bindOnlyWorldMatrix(world);
}
};
Mesh2.prototype.cleanMatrixWeights = function() {
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesWeightsKind)) {
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesWeightsExtraKind)) {
this.normalizeSkinWeightsAndExtra();
} else {
this.normalizeSkinFourWeights();
}
}
};
Mesh2.prototype.normalizeSkinFourWeights = function() {
var matricesWeights = this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind);
var numWeights = matricesWeights.length;
for (var a = 0; a < numWeights; a += 4) {
var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
if (t === 0) {
matricesWeights[a] = 1;
} else {
var recip = 1 / t;
matricesWeights[a] *= recip;
matricesWeights[a + 1] *= recip;
matricesWeights[a + 2] *= recip;
matricesWeights[a + 3] *= recip;
}
}
this.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, matricesWeights);
};
Mesh2.prototype.normalizeSkinWeightsAndExtra = function() {
var matricesWeightsExtra = this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
var matricesWeights = this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind);
var numWeights = matricesWeights.length;
for (var a = 0; a < numWeights; a += 4) {
var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
if (t === 0) {
matricesWeights[a] = 1;
} else {
var recip = 1 / t;
matricesWeights[a] *= recip;
matricesWeights[a + 1] *= recip;
matricesWeights[a + 2] *= recip;
matricesWeights[a + 3] *= recip;
matricesWeightsExtra[a] *= recip;
matricesWeightsExtra[a + 1] *= recip;
matricesWeightsExtra[a + 2] *= recip;
matricesWeightsExtra[a + 3] *= recip;
}
}
this.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, matricesWeights);
this.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
};
Mesh2.prototype.validateSkinning = function() {
var matricesWeightsExtra = this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
var matricesWeights = this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (matricesWeights === null || this.skeleton == null) {
return { skinned: false, valid: true, report: "not skinned" };
}
var numWeights = matricesWeights.length;
var numberNotSorted = 0;
var missingWeights = 0;
var maxUsedWeights = 0;
var numberNotNormalized = 0;
var numInfluences = matricesWeightsExtra === null ? 4 : 8;
var usedWeightCounts = new Array();
for (var a = 0; a <= numInfluences; a++) {
usedWeightCounts[a] = 0;
}
var toleranceEpsilon = 1e-3;
for (var a = 0; a < numWeights; a += 4) {
var lastWeight = matricesWeights[a];
var t = lastWeight;
var usedWeights = t === 0 ? 0 : 1;
for (var b2 = 1; b2 < numInfluences; b2++) {
var d = b2 < 4 ? matricesWeights[a + b2] : matricesWeightsExtra[a + b2 - 4];
if (d > lastWeight) {
numberNotSorted++;
}
if (d !== 0) {
usedWeights++;
}
t += d;
lastWeight = d;
}
usedWeightCounts[usedWeights]++;
if (usedWeights > maxUsedWeights) {
maxUsedWeights = usedWeights;
}
if (t === 0) {
missingWeights++;
} else {
var recip = 1 / t;
var tolerance = 0;
for (b2 = 0; b2 < numInfluences; b2++) {
if (b2 < 4) {
tolerance += Math.abs(matricesWeights[a + b2] - matricesWeights[a + b2] * recip);
} else {
tolerance += Math.abs(matricesWeightsExtra[a + b2 - 4] - matricesWeightsExtra[a + b2 - 4] * recip);
}
}
if (tolerance > toleranceEpsilon) {
numberNotNormalized++;
}
}
}
var numBones = this.skeleton.bones.length;
var matricesIndices = this.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind);
var matricesIndicesExtra = this.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
var numBadBoneIndices = 0;
for (var a = 0; a < numWeights; a++) {
for (var b2 = 0; b2 < numInfluences; b2++) {
var index = b2 < 4 ? matricesIndices[b2] : matricesIndicesExtra[b2 - 4];
if (index >= numBones || index < 0) {
numBadBoneIndices++;
}
}
}
var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights + "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted + "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
};
Mesh2.prototype._checkDelayState = function() {
var scene = this.getScene();
if (this._geometry) {
this._geometry.load(scene);
} else if (this.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED) {
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADING;
this._queueLoad(scene);
}
return this;
};
Mesh2.prototype._queueLoad = function(scene) {
var _this = this;
scene._addPendingData(this);
var getBinaryData = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1;
BABYLON2.Tools.LoadFile(this.delayLoadingFile, function(data2) {
if (data2 instanceof ArrayBuffer) {
_this._delayLoadingFunction(data2, _this);
} else {
_this._delayLoadingFunction(JSON.parse(data2), _this);
}
_this.instances.forEach(function(instance) {
instance._syncSubMeshes();
});
_this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADED;
scene._removePendingData(_this);
}, function() {
}, scene.database, getBinaryData);
return this;
};
Mesh2.prototype.isInFrustum = function(frustumPlanes) {
if (this.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_LOADING) {
return false;
}
if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
return false;
}
this._checkDelayState();
return true;
};
Mesh2.prototype.setMaterialByID = function(id) {
var materials = this.getScene().materials;
var index;
for (index = materials.length - 1; index > -1; index--) {
if (materials[index].id === id) {
this.material = materials[index];
return this;
}
}
var multiMaterials = this.getScene().multiMaterials;
for (index = multiMaterials.length - 1; index > -1; index--) {
if (multiMaterials[index].id === id) {
this.material = multiMaterials[index];
return this;
}
}
return this;
};
Mesh2.prototype.getAnimatables = function() {
var results = new Array();
if (this.material) {
results.push(this.material);
}
if (this.skeleton) {
results.push(this.skeleton);
}
return results;
};
Mesh2.prototype.bakeTransformIntoVertices = function(transform) {
if (!this.isVerticesDataPresent(BABYLON2.VertexBuffer.PositionKind)) {
return this;
}
var submeshes = this.subMeshes.splice(0);
this._resetPointsArrayCache();
var data2 = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var temp = new Array();
var index;
for (index = 0; index < data2.length; index += 3) {
BABYLON2.Vector3.TransformCoordinates(BABYLON2.Vector3.FromArray(data2, index), transform).toArray(temp, index);
}
this.setVerticesData(BABYLON2.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON2.VertexBuffer.PositionKind).isUpdatable());
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
data2 = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
temp = [];
for (index = 0; index < data2.length; index += 3) {
BABYLON2.Vector3.TransformNormal(BABYLON2.Vector3.FromArray(data2, index), transform).normalize().toArray(temp, index);
}
this.setVerticesData(BABYLON2.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON2.VertexBuffer.NormalKind).isUpdatable());
}
if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
this.flipFaces();
}
this.releaseSubMeshes();
this.subMeshes = submeshes;
return this;
};
Mesh2.prototype.bakeCurrentTransformIntoVertices = function() {
this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
this.scaling.copyFromFloats(1, 1, 1);
this.position.copyFromFloats(0, 0, 0);
this.rotation.copyFromFloats(0, 0, 0);
if (this.rotationQuaternion) {
this.rotationQuaternion = BABYLON2.Quaternion.Identity();
}
this._worldMatrix = BABYLON2.Matrix.Identity();
return this;
};
Object.defineProperty(Mesh2.prototype, "_positions", {
// Cache
/** @hidden */
get: function() {
if (this._geometry) {
return this._geometry._positions;
}
return null;
},
enumerable: true,
configurable: true
});
Mesh2.prototype._resetPointsArrayCache = function() {
if (this._geometry) {
this._geometry._resetPointsArrayCache();
}
return this;
};
Mesh2.prototype._generatePointsArray = function() {
if (this._geometry) {
return this._geometry._generatePointsArray();
}
return false;
};
Mesh2.prototype.clone = function(name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
if (name === void 0) {
name = "";
}
if (clonePhysicsImpostor === void 0) {
clonePhysicsImpostor = true;
}
return new Mesh2(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
};
Mesh2.prototype.dispose = function(doNotRecurse, disposeMaterialAndTextures) {
var _this = this;
if (disposeMaterialAndTextures === void 0) {
disposeMaterialAndTextures = false;
}
this.morphTargetManager = null;
if (this._geometry) {
this._geometry.releaseForMesh(this, true);
}
if (this._onBeforeDrawObservable) {
this._onBeforeDrawObservable.clear();
}
if (this._onBeforeRenderObservable) {
this._onBeforeRenderObservable.clear();
}
if (this._onAfterRenderObservable) {
this._onAfterRenderObservable.clear();
}
var meshes = this.getScene().meshes;
meshes.forEach(function(abstractMesh) {
var mesh2 = abstractMesh;
if (mesh2._source && mesh2._source === _this) {
mesh2._source = null;
}
});
this._source = null;
if (this._instanceDataStorage.instancesBuffer) {
this._instanceDataStorage.instancesBuffer.dispose();
this._instanceDataStorage.instancesBuffer = null;
}
while (this.instances.length) {
this.instances[0].dispose();
}
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
Mesh2.prototype.applyDisplacementMap = function(url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
var _this = this;
if (forceUpdate === void 0) {
forceUpdate = false;
}
var scene = this.getScene();
var onload = function(img) {
var canvas2 = document.createElement("canvas");
var context = canvas2.getContext("2d");
var heightMapWidth = img.width;
var heightMapHeight = img.height;
canvas2.width = heightMapWidth;
canvas2.height = heightMapHeight;
context.drawImage(img, 0, 0);
var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
_this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
if (onSuccess) {
onSuccess(_this);
}
};
BABYLON2.Tools.LoadImage(url, onload, function() {
}, scene.database);
return this;
};
Mesh2.prototype.applyDisplacementMapFromBuffer = function(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
if (forceUpdate === void 0) {
forceUpdate = false;
}
if (!this.isVerticesDataPresent(BABYLON2.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
BABYLON2.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
return this;
}
var positions = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind, true, true);
var normals = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var uvs = this.getVerticesData(BABYLON2.VertexBuffer.UVKind);
var position = BABYLON2.Vector3.Zero();
var normal = BABYLON2.Vector3.Zero();
var uv = BABYLON2.Vector2.Zero();
uvOffset = uvOffset || BABYLON2.Vector2.Zero();
uvScale = uvScale || new BABYLON2.Vector2(1, 1);
for (var index = 0; index < positions.length; index += 3) {
BABYLON2.Vector3.FromArrayToRef(positions, index, position);
BABYLON2.Vector3.FromArrayToRef(normals, index, normal);
BABYLON2.Vector2.FromArrayToRef(uvs, index / 3 * 2, uv);
var u = Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth % heightMapWidth | 0;
var v = Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight % heightMapHeight | 0;
var pos = (u + v * heightMapWidth) * 4;
var r = buffer[pos] / 255;
var g = buffer[pos + 1] / 255;
var b2 = buffer[pos + 2] / 255;
var gradient = r * 0.3 + g * 0.59 + b2 * 0.11;
normal.normalize();
normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
position = position.add(normal);
position.toArray(positions, index);
}
BABYLON2.VertexData.ComputeNormals(positions, this.getIndices(), normals);
if (forceUpdate) {
this.setVerticesData(BABYLON2.VertexBuffer.PositionKind, positions);
this.setVerticesData(BABYLON2.VertexBuffer.NormalKind, normals);
} else {
this.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, positions);
this.updateVerticesData(BABYLON2.VertexBuffer.NormalKind, normals);
}
return this;
};
Mesh2.prototype.convertToFlatShadedMesh = function() {
var kinds = this.getVerticesDataKinds();
var vbs = {};
var data2 = {};
var newdata = {};
var updatableNormals = false;
var kindIndex;
var kind;
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var vertexBuffer = this.getVertexBuffer(kind);
if (kind === BABYLON2.VertexBuffer.NormalKind) {
updatableNormals = vertexBuffer.isUpdatable();
kinds.splice(kindIndex, 1);
kindIndex--;
continue;
}
vbs[kind] = vertexBuffer;
data2[kind] = vbs[kind].getData();
newdata[kind] = [];
}
var previousSubmeshes = this.subMeshes.slice(0);
var indices = this.getIndices();
var totalIndices = this.getTotalIndices();
var index;
for (index = 0; index < totalIndices; index++) {
var vertexIndex = indices[index];
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var stride = vbs[kind].getStrideSize();
for (var offset = 0; offset < stride; offset++) {
newdata[kind].push(data2[kind][vertexIndex * stride + offset]);
}
}
}
var normals = [];
var positions = newdata[BABYLON2.VertexBuffer.PositionKind];
for (index = 0; index < totalIndices; index += 3) {
indices[index] = index;
indices[index + 1] = index + 1;
indices[index + 2] = index + 2;
var p1 = BABYLON2.Vector3.FromArray(positions, index * 3);
var p2 = BABYLON2.Vector3.FromArray(positions, (index + 1) * 3);
var p3 = BABYLON2.Vector3.FromArray(positions, (index + 2) * 3);
var p1p2 = p1.subtract(p2);
var p3p2 = p3.subtract(p2);
var normal = BABYLON2.Vector3.Normalize(BABYLON2.Vector3.Cross(p1p2, p3p2));
for (var localIndex = 0; localIndex < 3; localIndex++) {
normals.push(normal.x);
normals.push(normal.y);
normals.push(normal.z);
}
}
this.setIndices(indices);
this.setVerticesData(BABYLON2.VertexBuffer.NormalKind, normals, updatableNormals);
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
}
this.releaseSubMeshes();
for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
var previousOne = previousSubmeshes[submeshIndex];
BABYLON2.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
}
this.synchronizeInstances();
return this;
};
Mesh2.prototype.convertToUnIndexedMesh = function() {
var kinds = this.getVerticesDataKinds();
var vbs = {};
var data2 = {};
var newdata = {};
var kindIndex;
var kind;
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var vertexBuffer = this.getVertexBuffer(kind);
vbs[kind] = vertexBuffer;
data2[kind] = vbs[kind].getData();
newdata[kind] = [];
}
var previousSubmeshes = this.subMeshes.slice(0);
var indices = this.getIndices();
var totalIndices = this.getTotalIndices();
var index;
for (index = 0; index < totalIndices; index++) {
var vertexIndex = indices[index];
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
var stride = vbs[kind].getStrideSize();
for (var offset = 0; offset < stride; offset++) {
newdata[kind].push(data2[kind][vertexIndex * stride + offset]);
}
}
}
for (index = 0; index < totalIndices; index += 3) {
indices[index] = index;
indices[index + 1] = index + 1;
indices[index + 2] = index + 2;
}
this.setIndices(indices);
for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
kind = kinds[kindIndex];
this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
}
this.releaseSubMeshes();
for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
var previousOne = previousSubmeshes[submeshIndex];
BABYLON2.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
}
this._unIndexed = true;
this.synchronizeInstances();
return this;
};
Mesh2.prototype.flipFaces = function(flipNormals) {
if (flipNormals === void 0) {
flipNormals = false;
}
var vertex_data = BABYLON2.VertexData.ExtractFromMesh(this);
var i2;
if (flipNormals && this.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind) && vertex_data.normals) {
for (i2 = 0; i2 < vertex_data.normals.length; i2++) {
vertex_data.normals[i2] *= -1;
}
}
if (vertex_data.indices) {
var temp;
for (i2 = 0; i2 < vertex_data.indices.length; i2 += 3) {
temp = vertex_data.indices[i2 + 1];
vertex_data.indices[i2 + 1] = vertex_data.indices[i2 + 2];
vertex_data.indices[i2 + 2] = temp;
}
}
vertex_data.applyToMesh(this);
return this;
};
Mesh2.prototype.createInstance = function(name) {
return new BABYLON2.InstancedMesh(name, this);
};
Mesh2.prototype.synchronizeInstances = function() {
for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
var instance = this.instances[instanceIndex];
instance._syncSubMeshes();
}
return this;
};
Mesh2.prototype.optimizeIndices = function(successCallback2) {
var _this = this;
var indices = this.getIndices();
var positions = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (!positions || !indices) {
return this;
}
var vectorPositions = new Array();
for (var pos = 0; pos < positions.length; pos = pos + 3) {
vectorPositions.push(BABYLON2.Vector3.FromArray(positions, pos));
}
var dupes = new Array();
BABYLON2.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function(iteration) {
var realPos = vectorPositions.length - 1 - iteration;
var testedPosition = vectorPositions[realPos];
for (var j = 0; j < realPos; ++j) {
var againstPosition = vectorPositions[j];
if (testedPosition.equals(againstPosition)) {
dupes[realPos] = j;
break;
}
}
}, function() {
for (var i2 = 0; i2 < indices.length; ++i2) {
indices[i2] = dupes[indices[i2]] || indices[i2];
}
var originalSubMeshes = _this.subMeshes.slice(0);
_this.setIndices(indices);
_this.subMeshes = originalSubMeshes;
if (successCallback2) {
successCallback2(_this);
}
});
return this;
};
Mesh2.prototype.serialize = function(serializationObject) {
serializationObject.name = this.name;
serializationObject.id = this.id;
serializationObject.type = this.getClassName();
if (BABYLON2.Tags && BABYLON2.Tags.HasTags(this)) {
serializationObject.tags = BABYLON2.Tags.GetTags(this);
}
serializationObject.position = this.position.asArray();
if (this.rotationQuaternion) {
serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
} else if (this.rotation) {
serializationObject.rotation = this.rotation.asArray();
}
serializationObject.scaling = this.scaling.asArray();
serializationObject.localMatrix = this.getPivotMatrix().asArray();
serializationObject.isEnabled = this.isEnabled(false);
serializationObject.isVisible = this.isVisible;
serializationObject.infiniteDistance = this.infiniteDistance;
serializationObject.pickable = this.isPickable;
serializationObject.receiveShadows = this.receiveShadows;
serializationObject.billboardMode = this.billboardMode;
serializationObject.visibility = this.visibility;
serializationObject.checkCollisions = this.checkCollisions;
serializationObject.isBlocker = this.isBlocker;
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
serializationObject.isUnIndexed = this.isUnIndexed;
var geometry = this._geometry;
if (geometry) {
var geometryId = geometry.id;
serializationObject.geometryId = geometryId;
serializationObject.subMeshes = [];
for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
var subMesh = this.subMeshes[subIndex];
serializationObject.subMeshes.push({
materialIndex: subMesh.materialIndex,
verticesStart: subMesh.verticesStart,
verticesCount: subMesh.verticesCount,
indexStart: subMesh.indexStart,
indexCount: subMesh.indexCount
});
}
}
if (this.material) {
serializationObject.materialId = this.material.id;
} else {
this.material = null;
}
if (this.morphTargetManager) {
serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
}
if (this.skeleton) {
serializationObject.skeletonId = this.skeleton.id;
}
var impostor = this.getPhysicsImpostor();
if (impostor) {
serializationObject.physicsMass = impostor.getParam("mass");
serializationObject.physicsFriction = impostor.getParam("friction");
serializationObject.physicsRestitution = impostor.getParam("mass");
serializationObject.physicsImpostor = impostor.type;
}
if (this.metadata) {
serializationObject.metadata = this.metadata;
}
serializationObject.instances = [];
for (var index = 0; index < this.instances.length; index++) {
var instance = this.instances[index];
if (instance.doNotSerialize) {
continue;
}
var serializationInstance = {
name: instance.name,
id: instance.id,
position: instance.position.asArray(),
scaling: instance.scaling.asArray()
};
if (instance.parent) {
serializationInstance.parentId = instance.parent.id;
}
if (instance.rotationQuaternion) {
serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
} else if (instance.rotation) {
serializationInstance.rotation = instance.rotation.asArray();
}
serializationObject.instances.push(serializationInstance);
BABYLON2.Animation.AppendSerializedAnimations(instance, serializationInstance);
serializationInstance.ranges = instance.serializeAnimationRanges();
}
BABYLON2.Animation.AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
serializationObject.layerMask = this.layerMask;
serializationObject.alphaIndex = this.alphaIndex;
serializationObject.hasVertexAlpha = this.hasVertexAlpha;
serializationObject.overlayAlpha = this.overlayAlpha;
serializationObject.overlayColor = this.overlayColor.asArray();
serializationObject.renderOverlay = this.renderOverlay;
serializationObject.applyFog = this.applyFog;
if (this.actionManager) {
serializationObject.actions = this.actionManager.serialize(this.name);
}
};
Mesh2.prototype._syncGeometryWithMorphTargetManager = function() {
if (!this.geometry) {
return;
}
this._markSubMeshesAsAttributesDirty();
var morphTargetManager = this._morphTargetManager;
if (morphTargetManager && morphTargetManager.vertexCount) {
if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
BABYLON2.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
this.morphTargetManager = null;
return;
}
for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
var morphTarget = morphTargetManager.getActiveTarget(index);
var positions = morphTarget.getPositions();
if (!positions) {
BABYLON2.Tools.Error("Invalid morph target. Target must have positions.");
return;
}
this.geometry.setVerticesData(BABYLON2.VertexBuffer.PositionKind + index, positions, false, 3);
var normals = morphTarget.getNormals();
if (normals) {
this.geometry.setVerticesData(BABYLON2.VertexBuffer.NormalKind + index, normals, false, 3);
}
var tangents = morphTarget.getTangents();
if (tangents) {
this.geometry.setVerticesData(BABYLON2.VertexBuffer.TangentKind + index, tangents, false, 3);
}
}
} else {
var index = 0;
while (this.geometry.isVerticesDataPresent(BABYLON2.VertexBuffer.PositionKind + index)) {
this.geometry.removeVerticesData(BABYLON2.VertexBuffer.PositionKind + index);
if (this.geometry.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind + index)) {
this.geometry.removeVerticesData(BABYLON2.VertexBuffer.NormalKind + index);
}
if (this.geometry.isVerticesDataPresent(BABYLON2.VertexBuffer.TangentKind + index)) {
this.geometry.removeVerticesData(BABYLON2.VertexBuffer.TangentKind + index);
}
index++;
}
}
};
Mesh2.Parse = function(parsedMesh, scene, rootUrl) {
var mesh2;
if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
mesh2 = BABYLON2.GroundMesh.Parse(parsedMesh, scene);
} else {
mesh2 = new Mesh2(parsedMesh.name, scene);
}
mesh2.id = parsedMesh.id;
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(mesh2, parsedMesh.tags);
}
mesh2.position = BABYLON2.Vector3.FromArray(parsedMesh.position);
if (parsedMesh.metadata !== void 0) {
mesh2.metadata = parsedMesh.metadata;
}
if (parsedMesh.rotationQuaternion) {
mesh2.rotationQuaternion = BABYLON2.Quaternion.FromArray(parsedMesh.rotationQuaternion);
} else if (parsedMesh.rotation) {
mesh2.rotation = BABYLON2.Vector3.FromArray(parsedMesh.rotation);
}
mesh2.scaling = BABYLON2.Vector3.FromArray(parsedMesh.scaling);
if (parsedMesh.localMatrix) {
mesh2.setPreTransformMatrix(BABYLON2.Matrix.FromArray(parsedMesh.localMatrix));
} else if (parsedMesh.pivotMatrix) {
mesh2.setPivotMatrix(BABYLON2.Matrix.FromArray(parsedMesh.pivotMatrix));
}
mesh2.setEnabled(parsedMesh.isEnabled);
mesh2.isVisible = parsedMesh.isVisible;
mesh2.infiniteDistance = parsedMesh.infiniteDistance;
mesh2.showBoundingBox = parsedMesh.showBoundingBox;
mesh2.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
if (parsedMesh.applyFog !== void 0) {
mesh2.applyFog = parsedMesh.applyFog;
}
if (parsedMesh.pickable !== void 0) {
mesh2.isPickable = parsedMesh.pickable;
}
if (parsedMesh.alphaIndex !== void 0) {
mesh2.alphaIndex = parsedMesh.alphaIndex;
}
mesh2.receiveShadows = parsedMesh.receiveShadows;
mesh2.billboardMode = parsedMesh.billboardMode;
if (parsedMesh.visibility !== void 0) {
mesh2.visibility = parsedMesh.visibility;
}
mesh2.checkCollisions = parsedMesh.checkCollisions;
if (parsedMesh.isBlocker !== void 0) {
mesh2.isBlocker = parsedMesh.isBlocker;
}
mesh2._shouldGenerateFlatShading = parsedMesh.useFlatShading;
if (parsedMesh.freezeWorldMatrix) {
mesh2._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
}
if (parsedMesh.parentId) {
mesh2._waitingParentId = parsedMesh.parentId;
}
if (parsedMesh.actions !== void 0) {
mesh2._waitingActions = parsedMesh.actions;
}
if (parsedMesh.overlayAlpha !== void 0) {
mesh2.overlayAlpha = parsedMesh.overlayAlpha;
}
if (parsedMesh.overlayColor !== void 0) {
mesh2.overlayColor = BABYLON2.Color3.FromArray(parsedMesh.overlayColor);
}
if (parsedMesh.renderOverlay !== void 0) {
mesh2.renderOverlay = parsedMesh.renderOverlay;
}
mesh2.isUnIndexed = !!parsedMesh.isUnIndexed;
mesh2.hasVertexAlpha = parsedMesh.hasVertexAlpha;
if (parsedMesh.delayLoadingFile) {
mesh2.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED;
mesh2.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
mesh2._boundingInfo = new BABYLON2.BoundingInfo(BABYLON2.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON2.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
if (parsedMesh._binaryInfo) {
mesh2._binaryInfo = parsedMesh._binaryInfo;
}
mesh2._delayInfo = [];
if (parsedMesh.hasUVs) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.UVKind);
}
if (parsedMesh.hasUVs2) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.UV2Kind);
}
if (parsedMesh.hasUVs3) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.UV3Kind);
}
if (parsedMesh.hasUVs4) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.UV4Kind);
}
if (parsedMesh.hasUVs5) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.UV5Kind);
}
if (parsedMesh.hasUVs6) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.UV6Kind);
}
if (parsedMesh.hasColors) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.ColorKind);
}
if (parsedMesh.hasMatricesIndices) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
}
if (parsedMesh.hasMatricesWeights) {
mesh2._delayInfo.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
}
mesh2._delayLoadingFunction = BABYLON2.Geometry._ImportGeometry;
if (BABYLON2.SceneLoader.ForceFullSceneLoadingForIncremental) {
mesh2._checkDelayState();
}
} else {
BABYLON2.Geometry._ImportGeometry(parsedMesh, mesh2);
}
if (parsedMesh.materialId) {
mesh2.setMaterialByID(parsedMesh.materialId);
} else {
mesh2.material = null;
}
if (parsedMesh.morphTargetManagerId > -1) {
mesh2.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
}
if (parsedMesh.skeletonId > -1) {
mesh2.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
if (parsedMesh.numBoneInfluencers) {
mesh2.numBoneInfluencers = parsedMesh.numBoneInfluencers;
}
}
if (parsedMesh.animations) {
for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
var parsedAnimation = parsedMesh.animations[animationIndex];
mesh2.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
BABYLON2.Node.ParseAnimationRanges(mesh2, parsedMesh, scene);
}
if (parsedMesh.autoAnimate) {
scene.beginAnimation(mesh2, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1);
}
if (parsedMesh.layerMask && !isNaN(parsedMesh.layerMask)) {
mesh2.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
} else {
mesh2.layerMask = 268435455;
}
if (parsedMesh.physicsImpostor) {
mesh2.physicsImpostor = new BABYLON2.PhysicsImpostor(mesh2, parsedMesh.physicsImpostor, {
mass: parsedMesh.physicsMass,
friction: parsedMesh.physicsFriction,
restitution: parsedMesh.physicsRestitution
}, scene);
}
if (parsedMesh.instances) {
for (var index = 0; index < parsedMesh.instances.length; index++) {
var parsedInstance = parsedMesh.instances[index];
var instance = mesh2.createInstance(parsedInstance.name);
if (parsedInstance.id) {
instance.id = parsedInstance.id;
}
if (BABYLON2.Tags) {
if (parsedInstance.tags) {
BABYLON2.Tags.AddTagsTo(instance, parsedInstance.tags);
} else {
BABYLON2.Tags.AddTagsTo(instance, parsedMesh.tags);
}
}
instance.position = BABYLON2.Vector3.FromArray(parsedInstance.position);
if (parsedInstance.parentId) {
instance._waitingParentId = parsedInstance.parentId;
}
if (parsedInstance.rotationQuaternion) {
instance.rotationQuaternion = BABYLON2.Quaternion.FromArray(parsedInstance.rotationQuaternion);
} else if (parsedInstance.rotation) {
instance.rotation = BABYLON2.Vector3.FromArray(parsedInstance.rotation);
}
instance.scaling = BABYLON2.Vector3.FromArray(parsedInstance.scaling);
if (parsedInstance.checkCollisions != void 0 && parsedInstance.checkCollisions != null) {
instance.checkCollisions = parsedInstance.checkCollisions;
}
if (parsedInstance.pickable != void 0 && parsedInstance.pickable != null) {
instance.isPickable = parsedInstance.pickable;
}
if (parsedInstance.showBoundingBox != void 0 && parsedInstance.showBoundingBox != null) {
instance.showBoundingBox = parsedInstance.showBoundingBox;
}
if (parsedInstance.showSubMeshesBoundingBox != void 0 && parsedInstance.showSubMeshesBoundingBox != null) {
instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
}
if (parsedInstance.alphaIndex != void 0 && parsedInstance.showSubMeshesBoundingBox != null) {
instance.alphaIndex = parsedInstance.alphaIndex;
}
if (parsedInstance.physicsImpostor) {
instance.physicsImpostor = new BABYLON2.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
mass: parsedInstance.physicsMass,
friction: parsedInstance.physicsFriction,
restitution: parsedInstance.physicsRestitution
}, scene);
}
if (parsedInstance.animations) {
for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
parsedAnimation = parsedInstance.animations[animationIndex];
instance.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
BABYLON2.Node.ParseAnimationRanges(instance, parsedInstance, scene);
if (parsedInstance.autoAnimate) {
scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1);
}
}
}
}
return mesh2;
};
Mesh2.CreateDisc = function(name, radius, tessellation, scene, updatable, sideOrientation) {
if (scene === void 0) {
scene = null;
}
var options = {
radius,
tessellation,
sideOrientation,
updatable
};
return BABYLON2.MeshBuilder.CreateDisc(name, options, scene);
};
Mesh2.CreateBox = function(name, size, scene, updatable, sideOrientation) {
if (scene === void 0) {
scene = null;
}
var options = {
size,
sideOrientation,
updatable
};
return BABYLON2.MeshBuilder.CreateBox(name, options, scene);
};
Mesh2.CreateCylinder = function(name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
if (scene === void 0 || !(scene instanceof BABYLON2.Scene)) {
if (scene !== void 0) {
sideOrientation = updatable || Mesh2.DEFAULTSIDE;
updatable = scene;
}
scene = subdivisions;
subdivisions = 1;
}
var options = {
height,
diameterTop,
diameterBottom,
tessellation,
subdivisions,
sideOrientation,
updatable
};
return BABYLON2.MeshBuilder.CreateCylinder(name, options, scene);
};
Mesh2.CreateLines = function(name, points, scene, updatable, instance) {
if (scene === void 0) {
scene = null;
}
if (updatable === void 0) {
updatable = false;
}
if (instance === void 0) {
instance = null;
}
var options = {
points,
updatable,
instance
};
return BABYLON2.MeshBuilder.CreateLines(name, options, scene);
};
Mesh2.CreatePlane = function(name, size, scene, updatable, sideOrientation) {
var options = {
size,
width: size,
height: size,
sideOrientation,
updatable
};
return BABYLON2.MeshBuilder.CreatePlane(name, options, scene);
};
Mesh2.prototype.setPositionsForCPUSkinning = function() {
if (!this._sourcePositions) {
var source = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (!source) {
return this._sourcePositions;
}
this._sourcePositions = new Float32Array(source);
if (!this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.PositionKind)) {
this.setVerticesData(BABYLON2.VertexBuffer.PositionKind, source, true);
}
}
return this._sourcePositions;
};
Mesh2.prototype.setNormalsForCPUSkinning = function() {
if (!this._sourceNormals) {
var source = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
if (!source) {
return this._sourceNormals;
}
this._sourceNormals = new Float32Array(source);
if (!this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.NormalKind)) {
this.setVerticesData(BABYLON2.VertexBuffer.NormalKind, source, true);
}
}
return this._sourceNormals;
};
Mesh2.prototype.applySkeleton = function(skeleton) {
if (!this.geometry) {
return this;
}
if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
return this;
}
this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
if (!this.isVerticesDataPresent(BABYLON2.VertexBuffer.PositionKind)) {
return this;
}
if (!this.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
return this;
}
if (!this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesIndicesKind)) {
return this;
}
if (!this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesWeightsKind)) {
return this;
}
if (!this._sourcePositions) {
var submeshes = this.subMeshes.slice();
this.setPositionsForCPUSkinning();
this.subMeshes = submeshes;
}
if (!this._sourceNormals) {
this.setNormalsForCPUSkinning();
}
var positionsData = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (!positionsData) {
return this;
}
if (!(positionsData instanceof Float32Array)) {
positionsData = new Float32Array(positionsData);
}
var normalsData = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
if (!normalsData) {
return this;
}
if (!(normalsData instanceof Float32Array)) {
normalsData = new Float32Array(normalsData);
}
var matricesIndicesData = this.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind);
var matricesWeightsData = this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (!matricesWeightsData || !matricesIndicesData) {
return this;
}
var needExtras = this.numBoneInfluencers > 4;
var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind) : null;
var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind) : null;
var skeletonMatrices = skeleton.getTransformMatrices(this);
var tempVector3 = BABYLON2.Vector3.Zero();
var finalMatrix = new BABYLON2.Matrix();
var tempMatrix = new BABYLON2.Matrix();
var matWeightIdx = 0;
var inf;
for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
var weight;
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsData[matWeightIdx + inf];
if (weight > 0) {
BABYLON2.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
}
if (needExtras) {
for (inf = 0; inf < 4; inf++) {
weight = matricesWeightsExtraData[matWeightIdx + inf];
if (weight > 0) {
BABYLON2.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
finalMatrix.addToSelf(tempMatrix);
}
}
}
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
tempVector3.toArray(positionsData, index);
BABYLON2.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
tempVector3.toArray(normalsData, index);
finalMatrix.reset();
}
this.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, positionsData);
this.updateVerticesData(BABYLON2.VertexBuffer.NormalKind, normalsData);
return this;
};
Mesh2.MinMax = function(meshes) {
var minVector = null;
var maxVector = null;
meshes.forEach(function(mesh2, index, array) {
var boundingInfo = mesh2.getBoundingInfo();
var boundingBox = boundingInfo.boundingBox;
if (!minVector || !maxVector) {
minVector = boundingBox.minimumWorld;
maxVector = boundingBox.maximumWorld;
} else {
minVector.minimizeInPlace(boundingBox.minimumWorld);
maxVector.maximizeInPlace(boundingBox.maximumWorld);
}
});
if (!minVector || !maxVector) {
return {
min: BABYLON2.Vector3.Zero(),
max: BABYLON2.Vector3.Zero()
};
}
return {
min: minVector,
max: maxVector
};
};
Mesh2.Center = function(meshesOrMinMaxVector) {
var minMaxVector = meshesOrMinMaxVector instanceof Array ? Mesh2.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
return BABYLON2.Vector3.Center(minMaxVector.min, minMaxVector.max);
};
Mesh2.MergeMeshes = function(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
if (disposeSource === void 0) {
disposeSource = true;
}
var index;
if (!allow32BitsIndices) {
var totalVertices = 0;
for (index = 0; index < meshes.length; index++) {
if (meshes[index]) {
totalVertices += meshes[index].getTotalVertices();
if (totalVertices > 65536) {
BABYLON2.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
return null;
}
}
}
}
var vertexData = null;
var otherVertexData;
var indiceArray = new Array();
var source = null;
for (index = 0; index < meshes.length; index++) {
if (meshes[index]) {
var wm = meshes[index].computeWorldMatrix(true);
otherVertexData = BABYLON2.VertexData.ExtractFromMesh(meshes[index], true, true);
otherVertexData.transform(wm);
if (vertexData) {
vertexData.merge(otherVertexData, allow32BitsIndices);
} else {
vertexData = otherVertexData;
source = meshes[index];
}
if (subdivideWithSubMeshes) {
indiceArray.push(meshes[index].getTotalIndices());
}
}
}
source = source;
if (!meshSubclass) {
meshSubclass = new Mesh2(source.name + "_merged", source.getScene());
}
vertexData.applyToMesh(meshSubclass);
meshSubclass.material = source.material;
meshSubclass.checkCollisions = source.checkCollisions;
if (disposeSource) {
for (index = 0; index < meshes.length; index++) {
if (meshes[index]) {
meshes[index].dispose();
}
}
}
if (subdivideWithSubMeshes) {
meshSubclass.releaseSubMeshes();
index = 0;
var offset = 0;
while (index < indiceArray.length) {
BABYLON2.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
offset += indiceArray[index];
index++;
}
}
return meshSubclass;
};
Mesh2.FRONTSIDE = 0;
Mesh2.BACKSIDE = 1;
Mesh2.DOUBLESIDE = 2;
Mesh2.DEFAULTSIDE = 0;
Mesh2.NO_CAP = 0;
Mesh2.CAP_START = 1;
Mesh2.CAP_END = 2;
Mesh2.CAP_ALL = 3;
return Mesh2;
}(BABYLON2.AbstractMesh)
);
BABYLON2.Mesh = Mesh;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BaseSubMesh = (
/** @class */
function() {
function BaseSubMesh2() {
}
Object.defineProperty(BaseSubMesh2.prototype, "effect", {
/**
* Gets associated effect
*/
get: function() {
return this._materialEffect;
},
enumerable: true,
configurable: true
});
BaseSubMesh2.prototype.setEffect = function(effect, defines) {
if (defines === void 0) {
defines = null;
}
if (this._materialEffect === effect) {
if (!effect) {
this._materialDefines = null;
}
return;
}
this._materialDefines = defines;
this._materialEffect = effect;
};
return BaseSubMesh2;
}()
);
BABYLON2.BaseSubMesh = BaseSubMesh;
var SubMesh = (
/** @class */
function(_super) {
__extends(SubMesh2, _super);
function SubMesh2(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh2, renderingMesh, createBoundingBox) {
if (createBoundingBox === void 0) {
createBoundingBox = true;
}
var _this = _super.call(this) || this;
_this.materialIndex = materialIndex;
_this.verticesStart = verticesStart;
_this.verticesCount = verticesCount;
_this.indexStart = indexStart;
_this.indexCount = indexCount;
_this._renderId = 0;
_this._mesh = mesh2;
_this._renderingMesh = renderingMesh || mesh2;
mesh2.subMeshes.push(_this);
_this._trianglePlanes = [];
_this._id = mesh2.subMeshes.length - 1;
if (createBoundingBox) {
_this.refreshBoundingInfo();
mesh2.computeWorldMatrix(true);
}
return _this;
}
SubMesh2.AddToMesh = function(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh2, renderingMesh, createBoundingBox) {
if (createBoundingBox === void 0) {
createBoundingBox = true;
}
return new SubMesh2(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh2, renderingMesh, createBoundingBox);
};
Object.defineProperty(SubMesh2.prototype, "IsGlobal", {
/**
* Returns true if this submesh covers the entire parent mesh
* @ignorenaming
*/
get: function() {
return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices();
},
enumerable: true,
configurable: true
});
SubMesh2.prototype.getBoundingInfo = function() {
if (this.IsGlobal) {
return this._mesh.getBoundingInfo();
}
return this._boundingInfo;
};
SubMesh2.prototype.setBoundingInfo = function(boundingInfo) {
this._boundingInfo = boundingInfo;
return this;
};
SubMesh2.prototype.getMesh = function() {
return this._mesh;
};
SubMesh2.prototype.getRenderingMesh = function() {
return this._renderingMesh;
};
SubMesh2.prototype.getMaterial = function() {
var rootMaterial = this._renderingMesh.material;
if (rootMaterial === null || rootMaterial === void 0) {
return this._mesh.getScene().defaultMaterial;
} else if (rootMaterial.getSubMaterial) {
var multiMaterial = rootMaterial;
var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
if (this._currentMaterial !== effectiveMaterial) {
this._currentMaterial = effectiveMaterial;
this._materialDefines = null;
}
return effectiveMaterial;
}
return rootMaterial;
};
SubMesh2.prototype.refreshBoundingInfo = function() {
this._lastColliderWorldVertices = null;
if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
return this;
}
var data2 = this._renderingMesh.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (!data2) {
this._boundingInfo = this._mesh.getBoundingInfo();
return this;
}
var indices = this._renderingMesh.getIndices();
var extend;
if (this.indexStart === 0 && this.indexCount === indices.length) {
var boundingInfo = this._renderingMesh.getBoundingInfo();
extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
} else {
extend = BABYLON2.Tools.ExtractMinAndMaxIndexed(data2, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
}
this._boundingInfo = new BABYLON2.BoundingInfo(extend.minimum, extend.maximum);
return this;
};
SubMesh2.prototype._checkCollision = function(collider) {
var boundingInfo = this.getBoundingInfo();
return boundingInfo._checkCollision(collider);
};
SubMesh2.prototype.updateBoundingInfo = function(world) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
this.refreshBoundingInfo();
boundingInfo = this.getBoundingInfo();
}
boundingInfo.update(world);
return this;
};
SubMesh2.prototype.isInFrustum = function(frustumPlanes) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return false;
}
return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
};
SubMesh2.prototype.isCompletelyInFrustum = function(frustumPlanes) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return false;
}
return boundingInfo.isCompletelyInFrustum(frustumPlanes);
};
SubMesh2.prototype.render = function(enableAlphaMode) {
this._renderingMesh.render(this, enableAlphaMode);
return this;
};
SubMesh2.prototype._getLinesIndexBuffer = function(indices, engine) {
if (!this._linesIndexBuffer) {
var linesIndices = [];
for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
}
this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
this._linesIndexCount = linesIndices.length;
}
return this._linesIndexBuffer;
};
SubMesh2.prototype.canIntersects = function(ray) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return false;
}
return ray.intersectsBox(boundingInfo.boundingBox);
};
SubMesh2.prototype.intersects = function(ray, positions, indices, fastCheck) {
var material = this.getMaterial();
if (!material) {
return null;
}
switch (material.fillMode) {
case BABYLON2.Material.PointListDrawMode:
case BABYLON2.Material.LineListDrawMode:
case BABYLON2.Material.LineLoopDrawMode:
case BABYLON2.Material.LineStripDrawMode:
case BABYLON2.Material.TriangleFanDrawMode:
case BABYLON2.Material.TriangleStripDrawMode:
return null;
}
if (BABYLON2.LinesMesh) {
var mesh2 = this._mesh instanceof BABYLON2.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
if (mesh2 instanceof BABYLON2.LinesMesh) {
var linesMesh = mesh2;
return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
}
}
return this._intersectTriangles(ray, positions, indices, fastCheck);
};
SubMesh2.prototype._intersectLines = function(ray, positions, indices, intersectionThreshold, fastCheck) {
var intersectInfo = null;
for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
var p0 = positions[indices[index]];
var p1 = positions[indices[index + 1]];
var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
if (length < 0) {
continue;
}
if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
intersectInfo = new BABYLON2.IntersectionInfo(null, null, length);
if (fastCheck) {
break;
}
}
}
return intersectInfo;
};
SubMesh2.prototype._intersectTriangles = function(ray, positions, indices, fastCheck) {
var intersectInfo = null;
for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
var p0 = positions[indices[index]];
var p1 = positions[indices[index + 1]];
var p2 = positions[indices[index + 2]];
var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
if (currentIntersectInfo) {
if (currentIntersectInfo.distance < 0) {
continue;
}
if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
intersectInfo = currentIntersectInfo;
intersectInfo.faceId = index / 3;
if (fastCheck) {
break;
}
}
}
}
return intersectInfo;
};
SubMesh2.prototype._rebuild = function() {
if (this._linesIndexBuffer) {
this._linesIndexBuffer = null;
}
};
SubMesh2.prototype.clone = function(newMesh, newRenderingMesh) {
var result = new SubMesh2(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
if (!this.IsGlobal) {
var boundingInfo = this.getBoundingInfo();
if (!boundingInfo) {
return result;
}
result._boundingInfo = new BABYLON2.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
}
return result;
};
SubMesh2.prototype.dispose = function() {
if (this._linesIndexBuffer) {
this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
this._linesIndexBuffer = null;
}
var index = this._mesh.subMeshes.indexOf(this);
this._mesh.subMeshes.splice(index, 1);
};
SubMesh2.CreateFromIndices = function(materialIndex, startIndex, indexCount, mesh2, renderingMesh) {
var minVertexIndex = Number.MAX_VALUE;
var maxVertexIndex = -Number.MAX_VALUE;
renderingMesh = renderingMesh || mesh2;
var indices = renderingMesh.getIndices();
for (var index = startIndex; index < startIndex + indexCount; index++) {
var vertexIndex = indices[index];
if (vertexIndex < minVertexIndex) {
minVertexIndex = vertexIndex;
}
if (vertexIndex > maxVertexIndex) {
maxVertexIndex = vertexIndex;
}
}
return new SubMesh2(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh2, renderingMesh);
};
return SubMesh2;
}(BaseSubMesh)
);
BABYLON2.SubMesh = SubMesh;
})(BABYLON || (BABYLON = {}));
var __assign = function() {
__assign = Object.assign || function(t) {
for (var s, i2 = 1, n = arguments.length; i2 < n; i2++) {
s = arguments[i2];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var BABYLON;
(function(BABYLON2) {
var MaterialDefines = (
/** @class */
function() {
function MaterialDefines2() {
this._isDirty = true;
this._areLightsDirty = true;
this._areAttributesDirty = true;
this._areTexturesDirty = true;
this._areFresnelDirty = true;
this._areMiscDirty = true;
this._areImageProcessingDirty = true;
this._normals = false;
this._uvs = false;
this._needNormals = false;
this._needUVs = false;
}
Object.defineProperty(MaterialDefines2.prototype, "isDirty", {
/**
* Specifies if the material needs to be re-calculated
*/
get: function() {
return this._isDirty;
},
enumerable: true,
configurable: true
});
MaterialDefines2.prototype.markAsProcessed = function() {
this._isDirty = false;
this._areAttributesDirty = false;
this._areTexturesDirty = false;
this._areFresnelDirty = false;
this._areLightsDirty = false;
this._areMiscDirty = false;
this._areImageProcessingDirty = false;
};
MaterialDefines2.prototype.markAsUnprocessed = function() {
this._isDirty = true;
};
MaterialDefines2.prototype.markAllAsDirty = function() {
this._areTexturesDirty = true;
this._areAttributesDirty = true;
this._areLightsDirty = true;
this._areFresnelDirty = true;
this._areMiscDirty = true;
this._areImageProcessingDirty = true;
this._isDirty = true;
};
MaterialDefines2.prototype.markAsImageProcessingDirty = function() {
this._areImageProcessingDirty = true;
this._isDirty = true;
};
MaterialDefines2.prototype.markAsLightDirty = function() {
this._areLightsDirty = true;
this._isDirty = true;
};
MaterialDefines2.prototype.markAsAttributesDirty = function() {
this._areAttributesDirty = true;
this._isDirty = true;
};
MaterialDefines2.prototype.markAsTexturesDirty = function() {
this._areTexturesDirty = true;
this._isDirty = true;
};
MaterialDefines2.prototype.markAsFresnelDirty = function() {
this._areFresnelDirty = true;
this._isDirty = true;
};
MaterialDefines2.prototype.markAsMiscDirty = function() {
this._areMiscDirty = true;
this._isDirty = true;
};
MaterialDefines2.prototype.rebuild = function() {
if (this._keys) {
delete this._keys;
}
this._keys = [];
for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
var key = _a[_i];
if (key[0] === "_") {
continue;
}
this._keys.push(key);
}
};
MaterialDefines2.prototype.isEqual = function(other) {
if (this._keys.length !== other._keys.length) {
return false;
}
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
if (this[prop] !== other[prop]) {
return false;
}
}
return true;
};
MaterialDefines2.prototype.cloneTo = function(other) {
if (this._keys.length !== other._keys.length) {
other._keys = this._keys.slice(0);
}
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
other[prop] = this[prop];
}
};
MaterialDefines2.prototype.reset = function() {
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
var type = typeof this[prop];
switch (type) {
case "number":
this[prop] = 0;
break;
case "string":
this[prop] = "";
break;
default:
this[prop] = false;
break;
}
}
};
MaterialDefines2.prototype.toString = function() {
var result = "";
for (var index = 0; index < this._keys.length; index++) {
var prop = this._keys[index];
var value = this[prop];
var type = typeof value;
switch (type) {
case "number":
case "string":
result += "#define " + prop + " " + value + "\n";
break;
default:
if (value) {
result += "#define " + prop + "\n";
}
break;
}
}
return result;
};
return MaterialDefines2;
}()
);
BABYLON2.MaterialDefines = MaterialDefines;
var Material = (
/** @class */
function() {
function Material2(name, scene, doNotAdd) {
this.checkReadyOnEveryCall = false;
this.checkReadyOnlyOnce = false;
this.state = "";
this._alpha = 1;
this._backFaceCulling = true;
this.doNotSerialize = false;
this.storeEffectOnSubMeshes = false;
this.onDisposeObservable = new BABYLON2.Observable();
this._alphaMode = BABYLON2.Engine.ALPHA_COMBINE;
this._needDepthPrePass = false;
this.disableDepthWrite = false;
this.forceDepthWrite = false;
this.separateCullingPass = false;
this._fogEnabled = true;
this.pointSize = 1;
this.zOffset = 0;
this._wasPreviouslyReady = false;
this._fillMode = Material2.TriangleFillMode;
this.name = name;
this.id = name || BABYLON2.Tools.RandomId();
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
this.uniqueId = this._scene.getUniqueId();
if (this._scene.useRightHandedSystem) {
this.sideOrientation = Material2.ClockWiseSideOrientation;
} else {
this.sideOrientation = Material2.CounterClockWiseSideOrientation;
}
this._uniformBuffer = new BABYLON2.UniformBuffer(this._scene.getEngine());
this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
if (!doNotAdd) {
this._scene.materials.push(this);
this._scene.onNewMaterialAddedObservable.notifyObservers(this);
}
}
Object.defineProperty(Material2, "TriangleFillMode", {
/**
* Returns the triangle fill mode
*/
get: function() {
return Material2._TriangleFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "WireFrameFillMode", {
/**
* Returns the wireframe mode
*/
get: function() {
return Material2._WireFrameFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "PointFillMode", {
/**
* Returns the point fill mode
*/
get: function() {
return Material2._PointFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "PointListDrawMode", {
/**
* Returns the point list draw mode
*/
get: function() {
return Material2._PointListDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "LineListDrawMode", {
/**
* Returns the line list draw mode
*/
get: function() {
return Material2._LineListDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "LineLoopDrawMode", {
/**
* Returns the line loop draw mode
*/
get: function() {
return Material2._LineLoopDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "LineStripDrawMode", {
/**
* Returns the line strip draw mode
*/
get: function() {
return Material2._LineStripDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "TriangleStripDrawMode", {
/**
* Returns the triangle strip draw mode
*/
get: function() {
return Material2._TriangleStripDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "TriangleFanDrawMode", {
/**
* Returns the triangle fan draw mode
*/
get: function() {
return Material2._TriangleFanDrawMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "ClockWiseSideOrientation", {
/**
* Returns the clock-wise side orientation
*/
get: function() {
return Material2._ClockWiseSideOrientation;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2, "CounterClockWiseSideOrientation", {
/**
* Returns the counter clock-wise side orientation
*/
get: function() {
return Material2._CounterClockWiseSideOrientation;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "alpha", {
/**
* Gets the alpha value of the material
*/
get: function() {
return this._alpha;
},
/**
* Sets the alpha value of the material
*/
set: function(value) {
if (this._alpha === value) {
return;
}
this._alpha = value;
this.markAsDirty(Material2.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "backFaceCulling", {
/**
* Gets the back-face culling state
*/
get: function() {
return this._backFaceCulling;
},
/**
* Sets the back-face culling state
*/
set: function(value) {
if (this._backFaceCulling === value) {
return;
}
this._backFaceCulling = value;
this.markAsDirty(Material2.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "hasRenderTargetTextures", {
/**
* Gets a boolean indicating that current material needs to register RTT
*/
get: function() {
return false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "onDispose", {
/**
* Called during a dispose event
*/
set: function(callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "onBindObservable", {
/**
* An event triggered when the material is bound
*/
get: function() {
if (!this._onBindObservable) {
this._onBindObservable = new BABYLON2.Observable();
}
return this._onBindObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "onBind", {
/**
* Called during a bind event
*/
set: function(callback) {
if (this._onBindObserver) {
this.onBindObservable.remove(this._onBindObserver);
}
this._onBindObserver = this.onBindObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "onUnBindObservable", {
/**
* An event triggered when the material is unbound
*/
get: function() {
if (!this._onUnBindObservable) {
this._onUnBindObservable = new BABYLON2.Observable();
}
return this._onUnBindObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "alphaMode", {
/**
* Gets the value of the alpha mode
*/
get: function() {
return this._alphaMode;
},
/**
* Sets the value of the alpha mode.
*
* | Value | Type | Description |
* | --- | --- | --- |
* | 0 | ALPHA_DISABLE | |
* | 1 | ALPHA_ADD | |
* | 2 | ALPHA_COMBINE | |
* | 3 | ALPHA_SUBTRACT | |
* | 4 | ALPHA_MULTIPLY | |
* | 5 | ALPHA_MAXIMIZED | |
* | 6 | ALPHA_ONEONE | |
* | 7 | ALPHA_PREMULTIPLIED | |
* | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
* | 9 | ALPHA_INTERPOLATE | |
* | 10 | ALPHA_SCREENMODE | |
*
*/
set: function(value) {
if (this._alphaMode === value) {
return;
}
this._alphaMode = value;
this.markAsDirty(Material2.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "needDepthPrePass", {
/**
* Gets the depth pre-pass value
*/
get: function() {
return this._needDepthPrePass;
},
/**
* Sets the need depth pre-pass value
*/
set: function(value) {
if (this._needDepthPrePass === value) {
return;
}
this._needDepthPrePass = value;
if (this._needDepthPrePass) {
this.checkReadyOnEveryCall = true;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "fogEnabled", {
/**
* Gets the value of the fog enabled state
*/
get: function() {
return this._fogEnabled;
},
/**
* Sets the state for enabling fog
*/
set: function(value) {
if (this._fogEnabled === value) {
return;
}
this._fogEnabled = value;
this.markAsDirty(Material2.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "wireframe", {
/**
* Gets a value specifying if wireframe mode is enabled
*/
get: function() {
switch (this._fillMode) {
case Material2.WireFrameFillMode:
case Material2.LineListDrawMode:
case Material2.LineLoopDrawMode:
case Material2.LineStripDrawMode:
return true;
}
return this._scene.forceWireframe;
},
/**
* Sets the state of wireframe mode
*/
set: function(value) {
this.fillMode = value ? Material2.WireFrameFillMode : Material2.TriangleFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "pointsCloud", {
/**
* Gets the value specifying if point clouds are enabled
*/
get: function() {
switch (this._fillMode) {
case Material2.PointFillMode:
case Material2.PointListDrawMode:
return true;
}
return this._scene.forcePointsCloud;
},
/**
* Sets the state of point cloud mode
*/
set: function(value) {
this.fillMode = value ? Material2.PointFillMode : Material2.TriangleFillMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Material2.prototype, "fillMode", {
/**
* Gets the material fill mode
*/
get: function() {
return this._fillMode;
},
/**
* Sets the material fill mode
*/
set: function(value) {
if (this._fillMode === value) {
return;
}
this._fillMode = value;
this.markAsDirty(Material2.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
Material2.prototype.toString = function(fullDetails) {
var ret = "Name: " + this.name;
if (fullDetails) {
}
return ret;
};
Material2.prototype.getClassName = function() {
return "Material";
};
Object.defineProperty(Material2.prototype, "isFrozen", {
/**
* Specifies if updates for the material been locked
*/
get: function() {
return this.checkReadyOnlyOnce;
},
enumerable: true,
configurable: true
});
Material2.prototype.freeze = function() {
this.checkReadyOnlyOnce = true;
};
Material2.prototype.unfreeze = function() {
this.checkReadyOnlyOnce = false;
};
Material2.prototype.isReady = function(mesh2, useInstances) {
return true;
};
Material2.prototype.isReadyForSubMesh = function(mesh2, subMesh, useInstances) {
return false;
};
Material2.prototype.getEffect = function() {
return this._effect;
};
Material2.prototype.getScene = function() {
return this._scene;
};
Material2.prototype.needAlphaBlending = function() {
return this.alpha < 1;
};
Material2.prototype.needAlphaBlendingForMesh = function(mesh2) {
return this.needAlphaBlending() || mesh2.visibility < 1 || mesh2.hasVertexAlpha;
};
Material2.prototype.needAlphaTesting = function() {
return false;
};
Material2.prototype.getAlphaTestTexture = function() {
return null;
};
Material2.prototype.markDirty = function() {
this._wasPreviouslyReady = false;
};
Material2.prototype._preBind = function(effect, overrideOrientation) {
if (overrideOrientation === void 0) {
overrideOrientation = null;
}
var engine = this._scene.getEngine();
var orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation;
var reverse = orientation === Material2.ClockWiseSideOrientation;
engine.enableEffect(effect ? effect : this._effect);
engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
return reverse;
};
Material2.prototype.bind = function(world, mesh2) {
};
Material2.prototype.bindForSubMesh = function(world, mesh2, subMesh) {
};
Material2.prototype.bindOnlyWorldMatrix = function(world) {
};
Material2.prototype.bindSceneUniformBuffer = function(effect, sceneUbo) {
sceneUbo.bindToEffect(effect, "Scene");
};
Material2.prototype.bindView = function(effect) {
if (!this._useUBO) {
effect.setMatrix("view", this.getScene().getViewMatrix());
} else {
this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
}
};
Material2.prototype.bindViewProjection = function(effect) {
if (!this._useUBO) {
effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
} else {
this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
}
};
Material2.prototype._shouldTurnAlphaTestOn = function(mesh2) {
return !this.needAlphaBlendingForMesh(mesh2) && this.needAlphaTesting();
};
Material2.prototype._afterBind = function(mesh2) {
this._scene._cachedMaterial = this;
if (mesh2) {
this._scene._cachedVisibility = mesh2.visibility;
} else {
this._scene._cachedVisibility = 1;
}
if (this._onBindObservable && mesh2) {
this._onBindObservable.notifyObservers(mesh2);
}
if (this.disableDepthWrite) {
var engine = this._scene.getEngine();
this._cachedDepthWriteState = engine.getDepthWrite();
engine.setDepthWrite(false);
}
};
Material2.prototype.unbind = function() {
if (this._onUnBindObservable) {
this._onUnBindObservable.notifyObservers(this);
}
if (this.disableDepthWrite) {
var engine = this._scene.getEngine();
engine.setDepthWrite(this._cachedDepthWriteState);
}
};
Material2.prototype.getActiveTextures = function() {
return [];
};
Material2.prototype.hasTexture = function(texture) {
return false;
};
Material2.prototype.clone = function(name) {
return null;
};
Material2.prototype.getBindedMeshes = function() {
var result = new Array();
for (var index = 0; index < this._scene.meshes.length; index++) {
var mesh2 = this._scene.meshes[index];
if (mesh2.material === this) {
result.push(mesh2);
}
}
return result;
};
Material2.prototype.forceCompilation = function(mesh2, onCompiled, options) {
var _this = this;
var localOptions = __assign({ clipPlane: false }, options);
var subMesh = new BABYLON2.BaseSubMesh();
var scene = this.getScene();
var checkReady = function() {
if (!_this._scene || !_this._scene.getEngine()) {
return;
}
if (subMesh._materialDefines) {
subMesh._materialDefines._renderId = -1;
}
var clipPlaneState = scene.clipPlane;
if (localOptions.clipPlane) {
scene.clipPlane = new BABYLON2.Plane(0, 0, 0, 1);
}
if (_this.storeEffectOnSubMeshes) {
if (_this.isReadyForSubMesh(mesh2, subMesh)) {
if (onCompiled) {
onCompiled(_this);
}
} else {
setTimeout(checkReady, 16);
}
} else {
if (_this.isReady(mesh2)) {
if (onCompiled) {
onCompiled(_this);
}
} else {
setTimeout(checkReady, 16);
}
}
if (localOptions.clipPlane) {
scene.clipPlane = clipPlaneState;
}
};
checkReady();
};
Material2.prototype.forceCompilationAsync = function(mesh2, options) {
var _this = this;
return new Promise(function(resolve) {
_this.forceCompilation(mesh2, function() {
resolve();
}, options);
});
};
Material2.prototype.markAsDirty = function(flag) {
if (flag & Material2.TextureDirtyFlag) {
this._markAllSubMeshesAsTexturesDirty();
}
if (flag & Material2.LightDirtyFlag) {
this._markAllSubMeshesAsLightsDirty();
}
if (flag & Material2.FresnelDirtyFlag) {
this._markAllSubMeshesAsFresnelDirty();
}
if (flag & Material2.AttributesDirtyFlag) {
this._markAllSubMeshesAsAttributesDirty();
}
if (flag & Material2.MiscDirtyFlag) {
this._markAllSubMeshesAsMiscDirty();
}
this.getScene().resetCachedMaterial();
};
Material2.prototype._markAllSubMeshesAsDirty = function(func) {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
if (!mesh2.subMeshes) {
continue;
}
for (var _b = 0, _c = mesh2.subMeshes; _b < _c.length; _b++) {
var subMesh = _c[_b];
if (subMesh.getMaterial() !== this) {
continue;
}
if (!subMesh._materialDefines) {
continue;
}
func(subMesh._materialDefines);
}
}
};
Material2.prototype._markAllSubMeshesAsImageProcessingDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
return defines.markAsImageProcessingDirty();
});
};
Material2.prototype._markAllSubMeshesAsTexturesDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
return defines.markAsTexturesDirty();
});
};
Material2.prototype._markAllSubMeshesAsFresnelDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
return defines.markAsFresnelDirty();
});
};
Material2.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
defines.markAsFresnelDirty();
defines.markAsMiscDirty();
});
};
Material2.prototype._markAllSubMeshesAsLightsDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
return defines.markAsLightDirty();
});
};
Material2.prototype._markAllSubMeshesAsAttributesDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
return defines.markAsAttributesDirty();
});
};
Material2.prototype._markAllSubMeshesAsMiscDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
return defines.markAsMiscDirty();
});
};
Material2.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function() {
this._markAllSubMeshesAsDirty(function(defines) {
defines.markAsTexturesDirty();
defines.markAsMiscDirty();
});
};
Material2.prototype.dispose = function(forceDisposeEffect, forceDisposeTextures) {
this.getScene().stopAnimation(this);
this.getScene().freeProcessedMaterials();
var index = this._scene.materials.indexOf(this);
if (index >= 0) {
this._scene.materials.splice(index, 1);
}
this._scene.onMaterialRemovedObservable.notifyObservers(this);
for (index = 0; index < this._scene.meshes.length; index++) {
var mesh2 = this._scene.meshes[index];
if (mesh2.material === this) {
mesh2.material = null;
if (mesh2.geometry) {
var geometry = mesh2.geometry;
if (this.storeEffectOnSubMeshes) {
for (var _i = 0, _a = mesh2.subMeshes; _i < _a.length; _i++) {
var subMesh = _a[_i];
geometry._releaseVertexArrayObject(subMesh._materialEffect);
if (forceDisposeEffect && subMesh._materialEffect) {
this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
}
}
} else {
geometry._releaseVertexArrayObject(this._effect);
}
}
}
}
this._uniformBuffer.dispose();
if (forceDisposeEffect && this._effect) {
if (!this.storeEffectOnSubMeshes) {
this._scene.getEngine()._releaseEffect(this._effect);
}
this._effect = null;
}
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
if (this._onBindObservable) {
this._onBindObservable.clear();
}
if (this._onUnBindObservable) {
this._onUnBindObservable.clear();
}
};
Material2.prototype.serialize = function() {
return BABYLON2.SerializationHelper.Serialize(this);
};
Material2.ParseMultiMaterial = function(parsedMultiMaterial, scene) {
var multiMaterial = new BABYLON2.MultiMaterial(parsedMultiMaterial.name, scene);
multiMaterial.id = parsedMultiMaterial.id;
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
}
for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
var subMatId = parsedMultiMaterial.materials[matIndex];
if (subMatId) {
multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
} else {
multiMaterial.subMaterials.push(null);
}
}
return multiMaterial;
};
Material2.Parse = function(parsedMaterial, scene, rootUrl) {
if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
return BABYLON2.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
}
if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
if (!BABYLON2.LegacyPBRMaterial) {
BABYLON2.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
return;
}
}
var materialType = BABYLON2.Tools.Instantiate(parsedMaterial.customType);
return materialType.Parse(parsedMaterial, scene, rootUrl);
};
Material2._TriangleFillMode = 0;
Material2._WireFrameFillMode = 1;
Material2._PointFillMode = 2;
Material2._PointListDrawMode = 3;
Material2._LineListDrawMode = 4;
Material2._LineLoopDrawMode = 5;
Material2._LineStripDrawMode = 6;
Material2._TriangleStripDrawMode = 7;
Material2._TriangleFanDrawMode = 8;
Material2._ClockWiseSideOrientation = 0;
Material2._CounterClockWiseSideOrientation = 1;
Material2.TextureDirtyFlag = 1;
Material2.LightDirtyFlag = 2;
Material2.FresnelDirtyFlag = 4;
Material2.AttributesDirtyFlag = 8;
Material2.MiscDirtyFlag = 16;
Material2.AllDirtyFlag = 31;
__decorate([
BABYLON2.serialize()
], Material2.prototype, "id", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "uniqueId", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "name", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "checkReadyOnEveryCall", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "checkReadyOnlyOnce", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "state", void 0);
__decorate([
BABYLON2.serialize("alpha")
], Material2.prototype, "_alpha", void 0);
__decorate([
BABYLON2.serialize("backFaceCulling")
], Material2.prototype, "_backFaceCulling", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "sideOrientation", void 0);
__decorate([
BABYLON2.serialize("alphaMode")
], Material2.prototype, "_alphaMode", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "_needDepthPrePass", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "disableDepthWrite", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "forceDepthWrite", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "separateCullingPass", void 0);
__decorate([
BABYLON2.serialize("fogEnabled")
], Material2.prototype, "_fogEnabled", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "pointSize", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "zOffset", void 0);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "wireframe", null);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "pointsCloud", null);
__decorate([
BABYLON2.serialize()
], Material2.prototype, "fillMode", null);
return Material2;
}()
);
BABYLON2.Material = Material;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var UniformBuffer = (
/** @class */
function() {
function UniformBuffer2(engine, data2, dynamic) {
this._engine = engine;
this._noUBO = !engine.supportsUniformBuffers;
this._dynamic = dynamic;
this._data = data2 || [];
this._uniformLocations = {};
this._uniformSizes = {};
this._uniformLocationPointer = 0;
this._needSync = false;
if (this._noUBO) {
this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
this.updateFloat = this._updateFloatForEffect;
this.updateFloat2 = this._updateFloat2ForEffect;
this.updateFloat3 = this._updateFloat3ForEffect;
this.updateFloat4 = this._updateFloat4ForEffect;
this.updateMatrix = this._updateMatrixForEffect;
this.updateVector3 = this._updateVector3ForEffect;
this.updateVector4 = this._updateVector4ForEffect;
this.updateColor3 = this._updateColor3ForEffect;
this.updateColor4 = this._updateColor4ForEffect;
} else {
this._engine._uniformBuffers.push(this);
this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
this.updateFloat = this._updateFloatForUniform;
this.updateFloat2 = this._updateFloat2ForUniform;
this.updateFloat3 = this._updateFloat3ForUniform;
this.updateFloat4 = this._updateFloat4ForUniform;
this.updateMatrix = this._updateMatrixForUniform;
this.updateVector3 = this._updateVector3ForUniform;
this.updateVector4 = this._updateVector4ForUniform;
this.updateColor3 = this._updateColor3ForUniform;
this.updateColor4 = this._updateColor4ForUniform;
}
}
Object.defineProperty(UniformBuffer2.prototype, "useUbo", {
/**
* Indicates if the buffer is using the WebGL2 UBO implementation,
* or just falling back on setUniformXXX calls.
*/
get: function() {
return !this._noUBO;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UniformBuffer2.prototype, "isSync", {
/**
* Indicates if the WebGL underlying uniform buffer is in sync
* with the javascript cache data.
*/
get: function() {
return !this._needSync;
},
enumerable: true,
configurable: true
});
UniformBuffer2.prototype.isDynamic = function() {
return this._dynamic !== void 0;
};
UniformBuffer2.prototype.getData = function() {
return this._bufferData;
};
UniformBuffer2.prototype.getBuffer = function() {
return this._buffer;
};
UniformBuffer2.prototype._fillAlignment = function(size) {
var alignment;
if (size <= 2) {
alignment = size;
} else {
alignment = 4;
}
if (this._uniformLocationPointer % alignment !== 0) {
var oldPointer = this._uniformLocationPointer;
this._uniformLocationPointer += alignment - this._uniformLocationPointer % alignment;
var diff = this._uniformLocationPointer - oldPointer;
for (var i2 = 0; i2 < diff; i2++) {
this._data.push(0);
}
}
};
UniformBuffer2.prototype.addUniform = function(name, size) {
if (this._noUBO) {
return;
}
if (this._uniformLocations[name] !== void 0) {
return;
}
var data2;
if (size instanceof Array) {
data2 = size;
size = data2.length;
} else {
size = size;
data2 = [];
for (var i2 = 0; i2 < size; i2++) {
data2.push(0);
}
}
this._fillAlignment(size);
this._uniformSizes[name] = size;
this._uniformLocations[name] = this._uniformLocationPointer;
this._uniformLocationPointer += size;
for (var i2 = 0; i2 < size; i2++) {
this._data.push(data2[i2]);
}
this._needSync = true;
};
UniformBuffer2.prototype.addMatrix = function(name, mat) {
this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
};
UniformBuffer2.prototype.addFloat2 = function(name, x, y) {
var temp = [x, y];
this.addUniform(name, temp);
};
UniformBuffer2.prototype.addFloat3 = function(name, x, y, z) {
var temp = [x, y, z];
this.addUniform(name, temp);
};
UniformBuffer2.prototype.addColor3 = function(name, color) {
var temp = new Array();
color.toArray(temp);
this.addUniform(name, temp);
};
UniformBuffer2.prototype.addColor4 = function(name, color, alpha) {
var temp = new Array();
color.toArray(temp);
temp.push(alpha);
this.addUniform(name, temp);
};
UniformBuffer2.prototype.addVector3 = function(name, vector) {
var temp = new Array();
vector.toArray(temp);
this.addUniform(name, temp);
};
UniformBuffer2.prototype.addMatrix3x3 = function(name) {
this.addUniform(name, 12);
};
UniformBuffer2.prototype.addMatrix2x2 = function(name) {
this.addUniform(name, 8);
};
UniformBuffer2.prototype.create = function() {
if (this._noUBO) {
return;
}
if (this._buffer) {
return;
}
this._fillAlignment(4);
this._bufferData = new Float32Array(this._data);
this._rebuild();
this._needSync = true;
};
UniformBuffer2.prototype._rebuild = function() {
if (this._noUBO) {
return;
}
if (this._dynamic) {
this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
} else {
this._buffer = this._engine.createUniformBuffer(this._bufferData);
}
};
UniformBuffer2.prototype.update = function() {
if (!this._buffer) {
this.create();
return;
}
if (!this._dynamic && !this._needSync) {
return;
}
this._engine.updateUniformBuffer(this._buffer, this._bufferData);
this._needSync = false;
};
UniformBuffer2.prototype.updateUniform = function(uniformName, data2, size) {
var location2 = this._uniformLocations[uniformName];
if (location2 === void 0) {
if (this._buffer) {
BABYLON2.Tools.Error("Cannot add an uniform after UBO has been created.");
return;
}
this.addUniform(uniformName, size);
location2 = this._uniformLocations[uniformName];
}
if (!this._buffer) {
this.create();
}
if (!this._dynamic) {
var changed = false;
for (var i2 = 0; i2 < size; i2++) {
if (this._bufferData[location2 + i2] !== data2[i2]) {
changed = true;
this._bufferData[location2 + i2] = data2[i2];
}
}
this._needSync = this._needSync || changed;
} else {
for (var i2 = 0; i2 < size; i2++) {
this._bufferData[location2 + i2] = data2[i2];
}
}
};
UniformBuffer2.prototype._updateMatrix3x3ForUniform = function(name, matrix) {
for (var i2 = 0; i2 < 3; i2++) {
UniformBuffer2._tempBuffer[i2 * 4] = matrix[i2 * 3];
UniformBuffer2._tempBuffer[i2 * 4 + 1] = matrix[i2 * 3 + 1];
UniformBuffer2._tempBuffer[i2 * 4 + 2] = matrix[i2 * 3 + 2];
UniformBuffer2._tempBuffer[i2 * 4 + 3] = 0;
}
this.updateUniform(name, UniformBuffer2._tempBuffer, 12);
};
UniformBuffer2.prototype._updateMatrix3x3ForEffect = function(name, matrix) {
this._currentEffect.setMatrix3x3(name, matrix);
};
UniformBuffer2.prototype._updateMatrix2x2ForEffect = function(name, matrix) {
this._currentEffect.setMatrix2x2(name, matrix);
};
UniformBuffer2.prototype._updateMatrix2x2ForUniform = function(name, matrix) {
for (var i2 = 0; i2 < 2; i2++) {
UniformBuffer2._tempBuffer[i2 * 4] = matrix[i2 * 2];
UniformBuffer2._tempBuffer[i2 * 4 + 1] = matrix[i2 * 2 + 1];
UniformBuffer2._tempBuffer[i2 * 4 + 2] = 0;
UniformBuffer2._tempBuffer[i2 * 4 + 3] = 0;
}
this.updateUniform(name, UniformBuffer2._tempBuffer, 8);
};
UniformBuffer2.prototype._updateFloatForEffect = function(name, x) {
this._currentEffect.setFloat(name, x);
};
UniformBuffer2.prototype._updateFloatForUniform = function(name, x) {
UniformBuffer2._tempBuffer[0] = x;
this.updateUniform(name, UniformBuffer2._tempBuffer, 1);
};
UniformBuffer2.prototype._updateFloat2ForEffect = function(name, x, y, suffix) {
if (suffix === void 0) {
suffix = "";
}
this._currentEffect.setFloat2(name + suffix, x, y);
};
UniformBuffer2.prototype._updateFloat2ForUniform = function(name, x, y, suffix) {
if (suffix === void 0) {
suffix = "";
}
UniformBuffer2._tempBuffer[0] = x;
UniformBuffer2._tempBuffer[1] = y;
this.updateUniform(name, UniformBuffer2._tempBuffer, 2);
};
UniformBuffer2.prototype._updateFloat3ForEffect = function(name, x, y, z, suffix) {
if (suffix === void 0) {
suffix = "";
}
this._currentEffect.setFloat3(name + suffix, x, y, z);
};
UniformBuffer2.prototype._updateFloat3ForUniform = function(name, x, y, z, suffix) {
if (suffix === void 0) {
suffix = "";
}
UniformBuffer2._tempBuffer[0] = x;
UniformBuffer2._tempBuffer[1] = y;
UniformBuffer2._tempBuffer[2] = z;
this.updateUniform(name, UniformBuffer2._tempBuffer, 3);
};
UniformBuffer2.prototype._updateFloat4ForEffect = function(name, x, y, z, w, suffix) {
if (suffix === void 0) {
suffix = "";
}
this._currentEffect.setFloat4(name + suffix, x, y, z, w);
};
UniformBuffer2.prototype._updateFloat4ForUniform = function(name, x, y, z, w, suffix) {
if (suffix === void 0) {
suffix = "";
}
UniformBuffer2._tempBuffer[0] = x;
UniformBuffer2._tempBuffer[1] = y;
UniformBuffer2._tempBuffer[2] = z;
UniformBuffer2._tempBuffer[3] = w;
this.updateUniform(name, UniformBuffer2._tempBuffer, 4);
};
UniformBuffer2.prototype._updateMatrixForEffect = function(name, mat) {
this._currentEffect.setMatrix(name, mat);
};
UniformBuffer2.prototype._updateMatrixForUniform = function(name, mat) {
this.updateUniform(name, mat.toArray(), 16);
};
UniformBuffer2.prototype._updateVector3ForEffect = function(name, vector) {
this._currentEffect.setVector3(name, vector);
};
UniformBuffer2.prototype._updateVector3ForUniform = function(name, vector) {
vector.toArray(UniformBuffer2._tempBuffer);
this.updateUniform(name, UniformBuffer2._tempBuffer, 3);
};
UniformBuffer2.prototype._updateVector4ForEffect = function(name, vector) {
this._currentEffect.setVector4(name, vector);
};
UniformBuffer2.prototype._updateVector4ForUniform = function(name, vector) {
vector.toArray(UniformBuffer2._tempBuffer);
this.updateUniform(name, UniformBuffer2._tempBuffer, 4);
};
UniformBuffer2.prototype._updateColor3ForEffect = function(name, color, suffix) {
if (suffix === void 0) {
suffix = "";
}
this._currentEffect.setColor3(name + suffix, color);
};
UniformBuffer2.prototype._updateColor3ForUniform = function(name, color, suffix) {
if (suffix === void 0) {
suffix = "";
}
color.toArray(UniformBuffer2._tempBuffer);
this.updateUniform(name, UniformBuffer2._tempBuffer, 3);
};
UniformBuffer2.prototype._updateColor4ForEffect = function(name, color, alpha, suffix) {
if (suffix === void 0) {
suffix = "";
}
this._currentEffect.setColor4(name + suffix, color, alpha);
};
UniformBuffer2.prototype._updateColor4ForUniform = function(name, color, alpha, suffix) {
if (suffix === void 0) {
suffix = "";
}
color.toArray(UniformBuffer2._tempBuffer);
UniformBuffer2._tempBuffer[3] = alpha;
this.updateUniform(name, UniformBuffer2._tempBuffer, 4);
};
UniformBuffer2.prototype.setTexture = function(name, texture) {
this._currentEffect.setTexture(name, texture);
};
UniformBuffer2.prototype.updateUniformDirectly = function(uniformName, data2) {
this.updateUniform(uniformName, data2, data2.length);
this.update();
};
UniformBuffer2.prototype.bindToEffect = function(effect, name) {
this._currentEffect = effect;
if (this._noUBO || !this._buffer) {
return;
}
effect.bindUniformBuffer(this._buffer, name);
};
UniformBuffer2.prototype.dispose = function() {
if (this._noUBO) {
return;
}
var index = this._engine._uniformBuffers.indexOf(this);
if (index !== -1) {
this._engine._uniformBuffers.splice(index, 1);
}
if (!this._buffer) {
return;
}
if (this._engine._releaseBuffer(this._buffer)) {
this._buffer = null;
}
};
UniformBuffer2._MAX_UNIFORM_SIZE = 256;
UniformBuffer2._tempBuffer = new Float32Array(UniformBuffer2._MAX_UNIFORM_SIZE);
return UniformBuffer2;
}()
);
BABYLON2.UniformBuffer = UniformBuffer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var VertexData = (
/** @class */
function() {
function VertexData2() {
}
VertexData2.prototype.set = function(data2, kind) {
switch (kind) {
case BABYLON2.VertexBuffer.PositionKind:
this.positions = data2;
break;
case BABYLON2.VertexBuffer.NormalKind:
this.normals = data2;
break;
case BABYLON2.VertexBuffer.TangentKind:
this.tangents = data2;
break;
case BABYLON2.VertexBuffer.UVKind:
this.uvs = data2;
break;
case BABYLON2.VertexBuffer.UV2Kind:
this.uvs2 = data2;
break;
case BABYLON2.VertexBuffer.UV3Kind:
this.uvs3 = data2;
break;
case BABYLON2.VertexBuffer.UV4Kind:
this.uvs4 = data2;
break;
case BABYLON2.VertexBuffer.UV5Kind:
this.uvs5 = data2;
break;
case BABYLON2.VertexBuffer.UV6Kind:
this.uvs6 = data2;
break;
case BABYLON2.VertexBuffer.ColorKind:
this.colors = data2;
break;
case BABYLON2.VertexBuffer.MatricesIndicesKind:
this.matricesIndices = data2;
break;
case BABYLON2.VertexBuffer.MatricesWeightsKind:
this.matricesWeights = data2;
break;
case BABYLON2.VertexBuffer.MatricesIndicesExtraKind:
this.matricesIndicesExtra = data2;
break;
case BABYLON2.VertexBuffer.MatricesWeightsExtraKind:
this.matricesWeightsExtra = data2;
break;
}
};
VertexData2.prototype.applyToMesh = function(mesh2, updatable) {
this._applyTo(mesh2, updatable);
return this;
};
VertexData2.prototype.applyToGeometry = function(geometry, updatable) {
this._applyTo(geometry, updatable);
return this;
};
VertexData2.prototype.updateMesh = function(mesh2, updateExtends, makeItUnique) {
this._update(mesh2);
return this;
};
VertexData2.prototype.updateGeometry = function(geometry, updateExtends, makeItUnique) {
this._update(geometry);
return this;
};
VertexData2.prototype._applyTo = function(meshOrGeometry, updatable) {
if (updatable === void 0) {
updatable = false;
}
if (this.positions) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.PositionKind, this.positions, updatable);
}
if (this.normals) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.NormalKind, this.normals, updatable);
}
if (this.tangents) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.TangentKind, this.tangents, updatable);
}
if (this.uvs) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.UVKind, this.uvs, updatable);
}
if (this.uvs2) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.UV2Kind, this.uvs2, updatable);
}
if (this.uvs3) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.UV3Kind, this.uvs3, updatable);
}
if (this.uvs4) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.UV4Kind, this.uvs4, updatable);
}
if (this.uvs5) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.UV5Kind, this.uvs5, updatable);
}
if (this.uvs6) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.UV6Kind, this.uvs6, updatable);
}
if (this.colors) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.ColorKind, this.colors, updatable);
}
if (this.matricesIndices) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
}
if (this.matricesWeights) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
}
if (this.matricesIndicesExtra) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
}
if (this.matricesWeightsExtra) {
meshOrGeometry.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
}
if (this.indices) {
meshOrGeometry.setIndices(this.indices, null, updatable);
} else {
meshOrGeometry.setIndices([], null);
}
return this;
};
VertexData2.prototype._update = function(meshOrGeometry, updateExtends, makeItUnique) {
if (this.positions) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
}
if (this.normals) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
}
if (this.tangents) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
}
if (this.uvs) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
}
if (this.uvs2) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
}
if (this.uvs3) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
}
if (this.uvs4) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
}
if (this.uvs5) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
}
if (this.uvs6) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
}
if (this.colors) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
}
if (this.matricesIndices) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
}
if (this.matricesWeights) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
}
if (this.matricesIndicesExtra) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
}
if (this.matricesWeightsExtra) {
meshOrGeometry.updateVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
}
if (this.indices) {
meshOrGeometry.setIndices(this.indices, null);
}
return this;
};
VertexData2.prototype.transform = function(matrix) {
var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
var transformed = BABYLON2.Vector3.Zero();
var index;
if (this.positions) {
var position = BABYLON2.Vector3.Zero();
for (index = 0; index < this.positions.length; index += 3) {
BABYLON2.Vector3.FromArrayToRef(this.positions, index, position);
BABYLON2.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
this.positions[index] = transformed.x;
this.positions[index + 1] = transformed.y;
this.positions[index + 2] = transformed.z;
}
}
if (this.normals) {
var normal = BABYLON2.Vector3.Zero();
for (index = 0; index < this.normals.length; index += 3) {
BABYLON2.Vector3.FromArrayToRef(this.normals, index, normal);
BABYLON2.Vector3.TransformNormalToRef(normal, matrix, transformed);
this.normals[index] = transformed.x;
this.normals[index + 1] = transformed.y;
this.normals[index + 2] = transformed.z;
}
}
if (this.tangents) {
var tangent = BABYLON2.Vector4.Zero();
var tangentTransformed = BABYLON2.Vector4.Zero();
for (index = 0; index < this.tangents.length; index += 4) {
BABYLON2.Vector4.FromArrayToRef(this.tangents, index, tangent);
BABYLON2.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
this.tangents[index] = tangentTransformed.x;
this.tangents[index + 1] = tangentTransformed.y;
this.tangents[index + 2] = tangentTransformed.z;
this.tangents[index + 3] = tangentTransformed.w;
}
}
if (flip && this.indices) {
for (index = 0; index < this.indices.length; index += 3) {
var tmp = this.indices[index + 1];
this.indices[index + 1] = this.indices[index + 2];
this.indices[index + 2] = tmp;
}
}
return this;
};
VertexData2.prototype.merge = function(other, use32BitsIndices) {
if (use32BitsIndices === void 0) {
use32BitsIndices = false;
}
this._validate();
other._validate();
if (!this.normals !== !other.normals || !this.tangents !== !other.tangents || !this.uvs !== !other.uvs || !this.uvs2 !== !other.uvs2 || !this.uvs3 !== !other.uvs3 || !this.uvs4 !== !other.uvs4 || !this.uvs5 !== !other.uvs5 || !this.uvs6 !== !other.uvs6 || !this.colors !== !other.colors || !this.matricesIndices !== !other.matricesIndices || !this.matricesWeights !== !other.matricesWeights || !this.matricesIndicesExtra !== !other.matricesIndicesExtra || !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
throw new Error("Cannot merge vertex data that do not have the same set of attributes");
}
if (other.indices) {
if (!this.indices) {
this.indices = [];
}
var offset = this.positions ? this.positions.length / 3 : 0;
var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== void 0;
if (isSrcTypedArray) {
var len = this.indices.length + other.indices.length;
var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
temp.set(this.indices);
var decal = this.indices.length;
for (var index = 0; index < other.indices.length; index++) {
temp[decal + index] = other.indices[index] + offset;
}
this.indices = temp;
} else {
for (var index = 0; index < other.indices.length; index++) {
this.indices.push(other.indices[index] + offset);
}
}
}
this.positions = this._mergeElement(this.positions, other.positions);
this.normals = this._mergeElement(this.normals, other.normals);
this.tangents = this._mergeElement(this.tangents, other.tangents);
this.uvs = this._mergeElement(this.uvs, other.uvs);
this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
this.colors = this._mergeElement(this.colors, other.colors);
this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
return this;
};
VertexData2.prototype._mergeElement = function(source, other) {
if (!source) {
return other;
}
if (!other) {
return source;
}
var len = other.length + source.length;
var isSrcTypedArray = source instanceof Float32Array;
var isOthTypedArray = other instanceof Float32Array;
if (isSrcTypedArray) {
var ret32 = new Float32Array(len);
ret32.set(source);
ret32.set(other, source.length);
return ret32;
} else if (!isOthTypedArray) {
return source.concat(other);
} else {
var ret = source.slice(0);
for (var i2 = 0, len = other.length; i2 < len; i2++) {
ret.push(other[i2]);
}
return ret;
}
};
VertexData2.prototype._validate = function() {
if (!this.positions) {
throw new Error("Positions are required");
}
var getElementCount = function(kind, values) {
var stride = BABYLON2.VertexBuffer.DeduceStride(kind);
if (values.length % stride !== 0) {
throw new Error("The " + kind + "s array count must be a multiple of " + stride);
}
return values.length / stride;
};
var positionsElementCount = getElementCount(BABYLON2.VertexBuffer.PositionKind, this.positions);
var validateElementCount = function(kind, values) {
var elementCount = getElementCount(kind, values);
if (elementCount !== positionsElementCount) {
throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
}
};
if (this.normals) {
validateElementCount(BABYLON2.VertexBuffer.NormalKind, this.normals);
}
if (this.tangents) {
validateElementCount(BABYLON2.VertexBuffer.TangentKind, this.tangents);
}
if (this.uvs) {
validateElementCount(BABYLON2.VertexBuffer.UVKind, this.uvs);
}
if (this.uvs2) {
validateElementCount(BABYLON2.VertexBuffer.UV2Kind, this.uvs2);
}
if (this.uvs3) {
validateElementCount(BABYLON2.VertexBuffer.UV3Kind, this.uvs3);
}
if (this.uvs4) {
validateElementCount(BABYLON2.VertexBuffer.UV4Kind, this.uvs4);
}
if (this.uvs5) {
validateElementCount(BABYLON2.VertexBuffer.UV5Kind, this.uvs5);
}
if (this.uvs6) {
validateElementCount(BABYLON2.VertexBuffer.UV6Kind, this.uvs6);
}
if (this.colors) {
validateElementCount(BABYLON2.VertexBuffer.ColorKind, this.colors);
}
if (this.matricesIndices) {
validateElementCount(BABYLON2.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
}
if (this.matricesWeights) {
validateElementCount(BABYLON2.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
}
if (this.matricesIndicesExtra) {
validateElementCount(BABYLON2.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
}
if (this.matricesWeightsExtra) {
validateElementCount(BABYLON2.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
}
};
VertexData2.prototype.serialize = function() {
var serializationObject = this.serialize();
if (this.positions) {
serializationObject.positions = this.positions;
}
if (this.normals) {
serializationObject.normals = this.normals;
}
if (this.tangents) {
serializationObject.tangents = this.tangents;
}
if (this.uvs) {
serializationObject.uvs = this.uvs;
}
if (this.uvs2) {
serializationObject.uvs2 = this.uvs2;
}
if (this.uvs3) {
serializationObject.uvs3 = this.uvs3;
}
if (this.uvs4) {
serializationObject.uvs4 = this.uvs4;
}
if (this.uvs5) {
serializationObject.uvs5 = this.uvs5;
}
if (this.uvs6) {
serializationObject.uvs6 = this.uvs6;
}
if (this.colors) {
serializationObject.colors = this.colors;
}
if (this.matricesIndices) {
serializationObject.matricesIndices = this.matricesIndices;
serializationObject.matricesIndices._isExpanded = true;
}
if (this.matricesWeights) {
serializationObject.matricesWeights = this.matricesWeights;
}
if (this.matricesIndicesExtra) {
serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
serializationObject.matricesIndicesExtra._isExpanded = true;
}
if (this.matricesWeightsExtra) {
serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
}
serializationObject.indices = this.indices;
return serializationObject;
};
VertexData2.ExtractFromMesh = function(mesh2, copyWhenShared, forceCopy) {
return VertexData2._ExtractFrom(mesh2, copyWhenShared, forceCopy);
};
VertexData2.ExtractFromGeometry = function(geometry, copyWhenShared, forceCopy) {
return VertexData2._ExtractFrom(geometry, copyWhenShared, forceCopy);
};
VertexData2._ExtractFrom = function(meshOrGeometry, copyWhenShared, forceCopy) {
var result = new VertexData2();
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.PositionKind)) {
result.positions = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
result.normals = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.TangentKind)) {
result.tangents = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
result.uvs = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.UVKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind)) {
result.uvs2 = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.UV3Kind)) {
result.uvs3 = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.UV4Kind)) {
result.uvs4 = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.UV5Kind)) {
result.uvs5 = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.UV6Kind)) {
result.uvs6 = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.ColorKind)) {
result.colors = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesIndicesKind)) {
result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesWeightsKind)) {
result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesIndicesExtraKind)) {
result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
}
if (meshOrGeometry.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesWeightsExtraKind)) {
result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
}
result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
return result;
};
VertexData2.CreateRibbon = function(options) {
var pathArray = options.pathArray;
var closeArray = options.closeArray || false;
var closePath = options.closePath || false;
var invertUV = options.invertUV || false;
var defaultOffset = Math.floor(pathArray[0].length / 2);
var offset = options.offset || defaultOffset;
offset = offset > defaultOffset ? defaultOffset : Math.floor(offset);
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var customUV = options.uvs;
var customColors = options.colors;
var positions = [];
var indices = [];
var normals = [];
var uvs = [];
var us = [];
var vs = [];
var uTotalDistance = [];
var vTotalDistance = [];
var minlg;
var lg = [];
var idx = [];
var p;
var i2;
var j;
if (pathArray.length < 2) {
var ar1 = [];
var ar2 = [];
for (i2 = 0; i2 < pathArray[0].length - offset; i2++) {
ar1.push(pathArray[0][i2]);
ar2.push(pathArray[0][i2 + offset]);
}
pathArray = [ar1, ar2];
}
var idc = 0;
var closePathCorr = closePath ? 1 : 0;
var path;
var l;
minlg = pathArray[0].length;
var vectlg;
var dist;
for (p = 0; p < pathArray.length; p++) {
uTotalDistance[p] = 0;
us[p] = [0];
path = pathArray[p];
l = path.length;
minlg = minlg < l ? minlg : l;
j = 0;
while (j < l) {
positions.push(path[j].x, path[j].y, path[j].z);
if (j > 0) {
vectlg = path[j].subtract(path[j - 1]).length();
dist = vectlg + uTotalDistance[p];
us[p].push(dist);
uTotalDistance[p] = dist;
}
j++;
}
if (closePath) {
j--;
positions.push(path[0].x, path[0].y, path[0].z);
vectlg = path[j].subtract(path[0]).length();
dist = vectlg + uTotalDistance[p];
us[p].push(dist);
uTotalDistance[p] = dist;
}
lg[p] = l + closePathCorr;
idx[p] = idc;
idc += l + closePathCorr;
}
var path1;
var path2;
var vertex1 = null;
var vertex2 = null;
for (i2 = 0; i2 < minlg + closePathCorr; i2++) {
vTotalDistance[i2] = 0;
vs[i2] = [0];
for (p = 0; p < pathArray.length - 1; p++) {
path1 = pathArray[p];
path2 = pathArray[p + 1];
if (i2 === minlg) {
vertex1 = path1[0];
vertex2 = path2[0];
} else {
vertex1 = path1[i2];
vertex2 = path2[i2];
}
vectlg = vertex2.subtract(vertex1).length();
dist = vectlg + vTotalDistance[i2];
vs[i2].push(dist);
vTotalDistance[i2] = dist;
}
if (closeArray && vertex2 && vertex1) {
path1 = pathArray[p];
path2 = pathArray[0];
if (i2 === minlg) {
vertex2 = path2[0];
}
vectlg = vertex2.subtract(vertex1).length();
dist = vectlg + vTotalDistance[i2];
vTotalDistance[i2] = dist;
}
}
var u;
var v;
if (customUV) {
for (p = 0; p < customUV.length; p++) {
uvs.push(customUV[p].x, customUV[p].y);
}
} else {
for (p = 0; p < pathArray.length; p++) {
for (i2 = 0; i2 < minlg + closePathCorr; i2++) {
u = uTotalDistance[p] != 0 ? us[p][i2] / uTotalDistance[p] : 0;
v = vTotalDistance[i2] != 0 ? vs[i2][p] / vTotalDistance[i2] : 0;
if (invertUV) {
uvs.push(v, u);
} else {
uvs.push(u, v);
}
}
}
}
p = 0;
var pi = 0;
var l1 = lg[p] - 1;
var l2 = lg[p + 1] - 1;
var min = l1 < l2 ? l1 : l2;
var shft = idx[1] - idx[0];
var path1nb = closeArray ? lg.length : lg.length - 1;
while (pi <= min && p < path1nb) {
indices.push(pi, pi + shft, pi + 1);
indices.push(pi + shft + 1, pi + 1, pi + shft);
pi += 1;
if (pi === min) {
p++;
if (p === lg.length - 1) {
shft = idx[0] - idx[p];
l1 = lg[p] - 1;
l2 = lg[0] - 1;
} else {
shft = idx[p + 1] - idx[p];
l1 = lg[p] - 1;
l2 = lg[p + 1] - 1;
}
pi = idx[p];
min = l1 < l2 ? l1 + pi : l2 + pi;
}
}
VertexData2.ComputeNormals(positions, indices, normals);
if (closePath) {
var indexFirst = 0;
var indexLast = 0;
for (p = 0; p < pathArray.length; p++) {
indexFirst = idx[p] * 3;
if (p + 1 < pathArray.length) {
indexLast = (idx[p + 1] - 1) * 3;
} else {
indexLast = normals.length - 3;
}
normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
normals[indexLast] = normals[indexFirst];
normals[indexLast + 1] = normals[indexFirst + 1];
normals[indexLast + 2] = normals[indexFirst + 2];
}
}
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var colors = null;
if (customColors) {
colors = new Float32Array(customColors.length * 4);
for (var c = 0; c < customColors.length; c++) {
colors[c * 4] = customColors[c].r;
colors[c * 4 + 1] = customColors[c].g;
colors[c * 4 + 2] = customColors[c].b;
colors[c * 4 + 3] = customColors[c].a;
}
}
var vertexData = new VertexData2();
var positions32 = new Float32Array(positions);
var normals32 = new Float32Array(normals);
var uvs32 = new Float32Array(uvs);
vertexData.indices = indices;
vertexData.positions = positions32;
vertexData.normals = normals32;
vertexData.uvs = uvs32;
if (colors) {
vertexData.set(colors, BABYLON2.VertexBuffer.ColorKind);
}
if (closePath) {
vertexData._idx = idx;
}
return vertexData;
};
VertexData2.CreateBox = function(options) {
var normalsSource = [
new BABYLON2.Vector3(0, 0, 1),
new BABYLON2.Vector3(0, 0, -1),
new BABYLON2.Vector3(1, 0, 0),
new BABYLON2.Vector3(-1, 0, 0),
new BABYLON2.Vector3(0, 1, 0),
new BABYLON2.Vector3(0, -1, 0)
];
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var width = options.width || options.size || 1;
var height = options.height || options.size || 1;
var depth = options.depth || options.size || 1;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var faceUV = options.faceUV || new Array(6);
var faceColors = options.faceColors;
var colors = [];
for (var f = 0; f < 6; f++) {
if (faceUV[f] === void 0) {
faceUV[f] = new BABYLON2.Vector4(0, 0, 1, 1);
}
if (faceColors && faceColors[f] === void 0) {
faceColors[f] = new BABYLON2.Color4(1, 1, 1, 1);
}
}
var scaleVector = new BABYLON2.Vector3(width / 2, height / 2, depth / 2);
for (var index = 0; index < normalsSource.length; index++) {
var normal = normalsSource[index];
var side1 = new BABYLON2.Vector3(normal.y, normal.z, normal.x);
var side2 = BABYLON2.Vector3.Cross(normal, side1);
var verticesLength = positions.length / 3;
indices.push(verticesLength);
indices.push(verticesLength + 1);
indices.push(verticesLength + 2);
indices.push(verticesLength);
indices.push(verticesLength + 2);
indices.push(verticesLength + 3);
var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].z, faceUV[index].w);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].x, faceUV[index].w);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
vertex = normal.add(side1).add(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].x, faceUV[index].y);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(faceUV[index].z, faceUV[index].y);
if (faceColors) {
colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
}
}
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors) {
var totalColors = sideOrientation === BABYLON2.Mesh.DOUBLESIDE ? colors.concat(colors) : colors;
vertexData.colors = totalColors;
}
return vertexData;
};
VertexData2.CreateSphere = function(options) {
var segments = options.segments || 32;
var diameterX = options.diameterX || options.diameter || 1;
var diameterY = options.diameterY || options.diameter || 1;
var diameterZ = options.diameterZ || options.diameter || 1;
var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
var slice = options.slice && options.slice <= 0 ? 1 : options.slice || 1;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var radius = new BABYLON2.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
var totalZRotationSteps = 2 + segments;
var totalYRotationSteps = 2 * totalZRotationSteps;
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
var normalizedZ = zRotationStep / totalZRotationSteps;
var angleZ = normalizedZ * Math.PI * slice;
for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
var normalizedY = yRotationStep / totalYRotationSteps;
var angleY = normalizedY * Math.PI * 2 * arc;
var rotationZ = BABYLON2.Matrix.RotationZ(-angleZ);
var rotationY = BABYLON2.Matrix.RotationY(angleY);
var afterRotZ = BABYLON2.Vector3.TransformCoordinates(BABYLON2.Vector3.Up(), rotationZ);
var complete = BABYLON2.Vector3.TransformCoordinates(afterRotZ, rotationY);
var vertex = complete.multiply(radius);
var normal = complete.divide(radius).normalize();
positions.push(vertex.x, vertex.y, vertex.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(normalizedY, normalizedZ);
}
if (zRotationStep > 0) {
var verticesCount = positions.length / 3;
for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); firstIndex + totalYRotationSteps + 2 < verticesCount; firstIndex++) {
indices.push(firstIndex);
indices.push(firstIndex + 1);
indices.push(firstIndex + totalYRotationSteps + 1);
indices.push(firstIndex + totalYRotationSteps + 1);
indices.push(firstIndex + 1);
indices.push(firstIndex + totalYRotationSteps + 2);
}
}
}
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreateCylinder = function(options) {
var height = options.height || 2;
var diameterTop = options.diameterTop === 0 ? 0 : options.diameterTop || options.diameter || 1;
var diameterBottom = options.diameterBottom === 0 ? 0 : options.diameterBottom || options.diameter || 1;
var tessellation = options.tessellation || 24;
var subdivisions = options.subdivisions || 1;
var hasRings = options.hasRings ? true : false;
var enclose = options.enclose ? true : false;
var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var faceUV = options.faceUV || new Array(3);
var faceColors = options.faceColors;
var quadNb = arc !== 1 && enclose ? 2 : 0;
var ringNb = hasRings ? subdivisions : 1;
var surfaceNb = 2 + (1 + quadNb) * ringNb;
var f;
for (f = 0; f < surfaceNb; f++) {
if (faceColors && faceColors[f] === void 0) {
faceColors[f] = new BABYLON2.Color4(1, 1, 1, 1);
}
}
for (f = 0; f < surfaceNb; f++) {
if (faceUV && faceUV[f] === void 0) {
faceUV[f] = new BABYLON2.Vector4(0, 0, 1, 1);
}
}
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var colors = new Array();
var angle_step = Math.PI * 2 * arc / tessellation;
var angle;
var h;
var radius;
var tan = (diameterBottom - diameterTop) / 2 / height;
var ringVertex = BABYLON2.Vector3.Zero();
var ringNormal = BABYLON2.Vector3.Zero();
var ringFirstVertex = BABYLON2.Vector3.Zero();
var ringFirstNormal = BABYLON2.Vector3.Zero();
var quadNormal = BABYLON2.Vector3.Zero();
var Y = BABYLON2.Axis.Y;
var i2;
var j;
var r;
var ringIdx = 1;
var s = 1;
var cs = 0;
var v = 0;
for (i2 = 0; i2 <= subdivisions; i2++) {
h = i2 / subdivisions;
radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
ringIdx = hasRings && i2 !== 0 && i2 !== subdivisions ? 2 : 1;
for (r = 0; r < ringIdx; r++) {
if (hasRings) {
s += r;
}
if (enclose) {
s += 2 * r;
}
for (j = 0; j <= tessellation; j++) {
angle = j * angle_step;
ringVertex.x = Math.cos(-angle) * radius;
ringVertex.y = -height / 2 + h * height;
ringVertex.z = Math.sin(-angle) * radius;
if (diameterTop === 0 && i2 === subdivisions) {
ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
} else {
ringNormal.x = ringVertex.x;
ringNormal.z = ringVertex.z;
ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
ringNormal.normalize();
}
if (j === 0) {
ringFirstVertex.copyFrom(ringVertex);
ringFirstNormal.copyFrom(ringNormal);
}
positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
if (hasRings) {
v = cs !== s ? faceUV[s].y : faceUV[s].w;
} else {
v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
}
uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
if (faceColors) {
colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
}
}
if (arc !== 1 && enclose) {
positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
positions.push(0, ringVertex.y, 0);
positions.push(0, ringVertex.y, 0);
positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
BABYLON2.Vector3.CrossToRef(Y, ringNormal, quadNormal);
quadNormal.normalize();
normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
BABYLON2.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
quadNormal.normalize();
normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
if (hasRings) {
v = cs !== s ? faceUV[s + 1].y : faceUV[s + 1].w;
} else {
v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
}
uvs.push(faceUV[s + 1].x, v);
uvs.push(faceUV[s + 1].z, v);
if (hasRings) {
v = cs !== s ? faceUV[s + 2].y : faceUV[s + 2].w;
} else {
v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
}
uvs.push(faceUV[s + 2].x, v);
uvs.push(faceUV[s + 2].z, v);
if (faceColors) {
colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
}
}
if (cs !== s) {
cs = s;
}
}
}
var e2 = arc !== 1 && enclose ? tessellation + 4 : tessellation;
var s;
i2 = 0;
for (s = 0; s < subdivisions; s++) {
var i0 = 0;
var i1 = 0;
var i22 = 0;
var i3 = 0;
for (j = 0; j < tessellation; j++) {
i0 = i2 * (e2 + 1) + j;
i1 = (i2 + 1) * (e2 + 1) + j;
i22 = i2 * (e2 + 1) + (j + 1);
i3 = (i2 + 1) * (e2 + 1) + (j + 1);
indices.push(i0, i1, i22);
indices.push(i3, i22, i1);
}
if (arc !== 1 && enclose) {
indices.push(i0 + 2, i1 + 2, i22 + 2);
indices.push(i3 + 2, i22 + 2, i1 + 2);
indices.push(i0 + 4, i1 + 4, i22 + 4);
indices.push(i3 + 4, i22 + 4, i1 + 4);
}
i2 = hasRings ? i2 + 2 : i2 + 1;
}
var createCylinderCap = function(isTop) {
var radius2 = isTop ? diameterTop / 2 : diameterBottom / 2;
if (radius2 === 0) {
return;
}
var angle2;
var circleVector;
var i4;
var u = isTop ? faceUV[surfaceNb - 1] : faceUV[0];
var c = null;
if (faceColors) {
c = isTop ? faceColors[surfaceNb - 1] : faceColors[0];
}
var vbase = positions.length / 3;
var offset = isTop ? height / 2 : -height / 2;
var center = new BABYLON2.Vector3(0, offset, 0);
positions.push(center.x, center.y, center.z);
normals.push(0, isTop ? 1 : -1, 0);
uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
if (c) {
colors.push(c.r, c.g, c.b, c.a);
}
var textureScale = new BABYLON2.Vector2(0.5, 0.5);
for (i4 = 0; i4 <= tessellation; i4++) {
angle2 = Math.PI * 2 * i4 * arc / tessellation;
var cos = Math.cos(-angle2);
var sin = Math.sin(-angle2);
circleVector = new BABYLON2.Vector3(cos * radius2, offset, sin * radius2);
var textureCoordinate = new BABYLON2.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
positions.push(circleVector.x, circleVector.y, circleVector.z);
normals.push(0, isTop ? 1 : -1, 0);
uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
if (c) {
colors.push(c.r, c.g, c.b, c.a);
}
}
for (i4 = 0; i4 < tessellation; i4++) {
if (!isTop) {
indices.push(vbase);
indices.push(vbase + (i4 + 1));
indices.push(vbase + (i4 + 2));
} else {
indices.push(vbase);
indices.push(vbase + (i4 + 2));
indices.push(vbase + (i4 + 1));
}
}
};
createCylinderCap(false);
createCylinderCap(true);
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors) {
vertexData.colors = colors;
}
return vertexData;
};
VertexData2.CreateTorus = function(options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var diameter = options.diameter || 1;
var thickness = options.thickness || 0.5;
var tessellation = options.tessellation || 16;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var stride = tessellation + 1;
for (var i2 = 0; i2 <= tessellation; i2++) {
var u = i2 / tessellation;
var outerAngle = i2 * Math.PI * 2 / tessellation - Math.PI / 2;
var transform = BABYLON2.Matrix.Translation(diameter / 2, 0, 0).multiply(BABYLON2.Matrix.RotationY(outerAngle));
for (var j = 0; j <= tessellation; j++) {
var v = 1 - j / tessellation;
var innerAngle = j * Math.PI * 2 / tessellation + Math.PI;
var dx = Math.cos(innerAngle);
var dy = Math.sin(innerAngle);
var normal = new BABYLON2.Vector3(dx, dy, 0);
var position = normal.scale(thickness / 2);
var textureCoordinate = new BABYLON2.Vector2(u, v);
position = BABYLON2.Vector3.TransformCoordinates(position, transform);
normal = BABYLON2.Vector3.TransformNormal(normal, transform);
positions.push(position.x, position.y, position.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(textureCoordinate.x, textureCoordinate.y);
var nextI = (i2 + 1) % stride;
var nextJ = (j + 1) % stride;
indices.push(i2 * stride + j);
indices.push(i2 * stride + nextJ);
indices.push(nextI * stride + j);
indices.push(i2 * stride + nextJ);
indices.push(nextI * stride + nextJ);
indices.push(nextI * stride + j);
}
}
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreateLineSystem = function(options) {
var indices = [];
var positions = [];
var lines = options.lines;
var colors = options.colors;
var vertexColors = [];
var idx = 0;
for (var l = 0; l < lines.length; l++) {
var points = lines[l];
for (var index = 0; index < points.length; index++) {
positions.push(points[index].x, points[index].y, points[index].z);
if (colors) {
var color = colors[l];
vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
}
if (index > 0) {
indices.push(idx - 1);
indices.push(idx);
}
idx++;
}
}
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
if (colors) {
vertexData.colors = vertexColors;
}
return vertexData;
};
VertexData2.CreateDashedLines = function(options) {
var dashSize = options.dashSize || 3;
var gapSize = options.gapSize || 1;
var dashNb = options.dashNb || 200;
var points = options.points;
var positions = new Array();
var indices = new Array();
var curvect = BABYLON2.Vector3.Zero();
var lg = 0;
var nb = 0;
var shft = 0;
var dashshft = 0;
var curshft = 0;
var idx = 0;
var i2 = 0;
for (i2 = 0; i2 < points.length - 1; i2++) {
points[i2 + 1].subtractToRef(points[i2], curvect);
lg += curvect.length();
}
shft = lg / dashNb;
dashshft = dashSize * shft / (dashSize + gapSize);
for (i2 = 0; i2 < points.length - 1; i2++) {
points[i2 + 1].subtractToRef(points[i2], curvect);
nb = Math.floor(curvect.length() / shft);
curvect.normalize();
for (var j = 0; j < nb; j++) {
curshft = shft * j;
positions.push(points[i2].x + curshft * curvect.x, points[i2].y + curshft * curvect.y, points[i2].z + curshft * curvect.z);
positions.push(points[i2].x + (curshft + dashshft) * curvect.x, points[i2].y + (curshft + dashshft) * curvect.y, points[i2].z + (curshft + dashshft) * curvect.z);
indices.push(idx, idx + 1);
idx += 2;
}
}
var vertexData = new VertexData2();
vertexData.positions = positions;
vertexData.indices = indices;
return vertexData;
};
VertexData2.CreateGround = function(options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var row, col;
var width = options.width || 1;
var height = options.height || 1;
var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
for (row = 0; row <= subdivisionsY; row++) {
for (col = 0; col <= subdivisionsX; col++) {
var position = new BABYLON2.Vector3(col * width / subdivisionsX - width / 2, 0, (subdivisionsY - row) * height / subdivisionsY - height / 2);
var normal = new BABYLON2.Vector3(0, 1, 0);
positions.push(position.x, position.y, position.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(col / subdivisionsX, 1 - row / subdivisionsY);
}
}
for (row = 0; row < subdivisionsY; row++) {
for (col = 0; col < subdivisionsX; col++) {
indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
indices.push(col + 1 + row * (subdivisionsX + 1));
indices.push(col + row * (subdivisionsX + 1));
indices.push(col + (row + 1) * (subdivisionsX + 1));
indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
indices.push(col + row * (subdivisionsX + 1));
}
}
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreateTiledGround = function(options) {
var xmin = options.xmin !== void 0 && options.xmin !== null ? options.xmin : -1;
var zmin = options.zmin !== void 0 && options.zmin !== null ? options.zmin : -1;
var xmax = options.xmax !== void 0 && options.xmax !== null ? options.xmax : 1;
var zmax = options.zmax !== void 0 && options.zmax !== null ? options.zmax : 1;
var subdivisions = options.subdivisions || { w: 1, h: 1 };
var precision = options.precision || { w: 1, h: 1 };
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var row, col, tileRow, tileCol;
subdivisions.h = subdivisions.h < 1 ? 1 : subdivisions.h;
subdivisions.w = subdivisions.w < 1 ? 1 : subdivisions.w;
precision.w = precision.w < 1 ? 1 : precision.w;
precision.h = precision.h < 1 ? 1 : precision.h;
var tileSize = {
"w": (xmax - xmin) / subdivisions.w,
"h": (zmax - zmin) / subdivisions.h
};
function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
var base = positions.length / 3;
var rowLength = precision.w + 1;
for (row = 0; row < precision.h; row++) {
for (col = 0; col < precision.w; col++) {
var square = [
base + col + row * rowLength,
base + (col + 1) + row * rowLength,
base + (col + 1) + (row + 1) * rowLength,
base + col + (row + 1) * rowLength
];
indices.push(square[1]);
indices.push(square[2]);
indices.push(square[3]);
indices.push(square[0]);
indices.push(square[1]);
indices.push(square[3]);
}
}
var position = BABYLON2.Vector3.Zero();
var normal = new BABYLON2.Vector3(0, 1, 0);
for (row = 0; row <= precision.h; row++) {
position.z = row * (zTileMax - zTileMin) / precision.h + zTileMin;
for (col = 0; col <= precision.w; col++) {
position.x = col * (xTileMax - xTileMin) / precision.w + xTileMin;
position.y = 0;
positions.push(position.x, position.y, position.z);
normals.push(normal.x, normal.y, normal.z);
uvs.push(col / precision.w, row / precision.h);
}
}
}
for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
}
}
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreateGroundFromHeightMap = function(options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var row, col;
var filter = options.colorFilter || new BABYLON2.Color3(0.3, 0.59, 0.11);
var alphaFilter = options.alphaFilter || 0;
for (row = 0; row <= options.subdivisions; row++) {
for (col = 0; col <= options.subdivisions; col++) {
var position = new BABYLON2.Vector3(col * options.width / options.subdivisions - options.width / 2, 0, (options.subdivisions - row) * options.height / options.subdivisions - options.height / 2);
var heightMapX = (position.x + options.width / 2) / options.width * (options.bufferWidth - 1) | 0;
var heightMapY = (1 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1) | 0;
var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
var r = options.buffer[pos] / 255;
var g = options.buffer[pos + 1] / 255;
var b2 = options.buffer[pos + 2] / 255;
var a = options.buffer[pos + 3] / 255;
var gradient = r * filter.r + g * filter.g + b2 * filter.b;
if (a >= alphaFilter) {
position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
} else {
position.y = options.minHeight - BABYLON2.Epsilon;
}
positions.push(position.x, position.y, position.z);
normals.push(0, 0, 0);
uvs.push(col / options.subdivisions, 1 - row / options.subdivisions);
}
}
for (row = 0; row < options.subdivisions; row++) {
for (col = 0; col < options.subdivisions; col++) {
var idx1 = col + 1 + (row + 1) * (options.subdivisions + 1);
var idx2 = col + 1 + row * (options.subdivisions + 1);
var idx3 = col + row * (options.subdivisions + 1);
var idx4 = col + (row + 1) * (options.subdivisions + 1);
var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
indices.push(idx1);
indices.push(idx2);
indices.push(idx3);
}
var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
indices.push(idx4);
indices.push(idx1);
indices.push(idx3);
}
}
}
VertexData2.ComputeNormals(positions, indices, normals);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreatePlane = function(options) {
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
var width = options.width || options.size || 1;
var height = options.height || options.size || 1;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var halfWidth = width / 2;
var halfHeight = height / 2;
positions.push(-halfWidth, -halfHeight, 0);
normals.push(0, 0, -1);
uvs.push(0, 0);
positions.push(halfWidth, -halfHeight, 0);
normals.push(0, 0, -1);
uvs.push(1, 0);
positions.push(halfWidth, halfHeight, 0);
normals.push(0, 0, -1);
uvs.push(1, 1);
positions.push(-halfWidth, halfHeight, 0);
normals.push(0, 0, -1);
uvs.push(0, 1);
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreateDisc = function(options) {
var positions = new Array();
var indices = new Array();
var normals = new Array();
var uvs = new Array();
var radius = options.radius || 0.5;
var tessellation = options.tessellation || 64;
var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
positions.push(0, 0, 0);
uvs.push(0.5, 0.5);
var theta = Math.PI * 2 * arc;
var step = theta / tessellation;
for (var a = 0; a < theta; a += step) {
var x = Math.cos(a);
var y = Math.sin(a);
var u = (x + 1) / 2;
var v = (1 - y) / 2;
positions.push(radius * x, radius * y, 0);
uvs.push(u, v);
}
if (arc === 1) {
positions.push(positions[3], positions[4], positions[5]);
uvs.push(uvs[2], uvs[3]);
}
var vertexNb = positions.length / 3;
for (var i2 = 1; i2 < vertexNb - 1; i2++) {
indices.push(i2 + 1, 0, i2);
}
VertexData2.ComputeNormals(positions, indices, normals);
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreatePolygon = function(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
var faceUV = fUV || new Array(3);
var faceColors = fColors;
var colors = [];
for (var f = 0; f < 3; f++) {
if (faceUV[f] === void 0) {
faceUV[f] = new BABYLON2.Vector4(0, 0, 1, 1);
}
if (faceColors && faceColors[f] === void 0) {
faceColors[f] = new BABYLON2.Color4(1, 1, 1, 1);
}
}
var positions = polygon.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var normals = polygon.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var uvs = polygon.getVerticesData(BABYLON2.VertexBuffer.UVKind);
var indices = polygon.getIndices();
var idx = 0;
var face = 0;
for (var index = 0; index < normals.length; index += 3) {
if (Math.abs(normals[index + 1]) < 1e-3) {
face = 1;
}
if (Math.abs(normals[index + 1] - 1) < 1e-3) {
face = 0;
}
if (Math.abs(normals[index + 1] + 1) < 1e-3) {
face = 2;
}
idx = index / 3;
uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
if (faceColors) {
colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
}
}
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors) {
var totalColors = sideOrientation === BABYLON2.Mesh.DOUBLESIDE ? colors.concat(colors) : colors;
vertexData.colors = totalColors;
}
return vertexData;
};
VertexData2.CreateIcoSphere = function(options) {
var sideOrientation = options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var radius = options.radius || 1;
var flat = options.flat === void 0 ? true : options.flat;
var subdivisions = options.subdivisions || 4;
var radiusX = options.radiusX || radius;
var radiusY = options.radiusY || radius;
var radiusZ = options.radiusZ || radius;
var t = (1 + Math.sqrt(5)) / 2;
var ico_vertices = [
-1,
t,
-0,
1,
t,
0,
-1,
-t,
0,
1,
-t,
0,
0,
-1,
-t,
0,
1,
-t,
0,
-1,
t,
0,
1,
t,
t,
0,
1,
t,
0,
-1,
-t,
0,
1,
-t,
0,
-1
// v8-11
];
var ico_indices = [
0,
11,
5,
0,
5,
1,
0,
1,
7,
0,
7,
10,
12,
22,
23,
1,
5,
20,
5,
11,
4,
23,
22,
13,
22,
18,
6,
7,
1,
8,
14,
21,
4,
14,
4,
2,
16,
13,
6,
15,
6,
19,
3,
8,
9,
4,
21,
5,
13,
17,
23,
6,
13,
22,
19,
6,
18,
9,
8,
1
];
var vertices_unalias_id = [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
// vertex alias
0,
2,
3,
3,
3,
4,
7,
8,
9,
9,
10,
11
// 23: B + 12
];
var ico_vertexuv = [
5,
1,
3,
1,
6,
4,
0,
0,
5,
3,
4,
2,
2,
2,
4,
0,
2,
0,
1,
1,
6,
0,
6,
2,
// vertex alias (for same vertex on different faces)
0,
4,
3,
3,
4,
4,
3,
1,
4,
2,
4,
4,
0,
2,
1,
1,
2,
2,
3,
3,
1,
3,
2,
4
// 23: B + 12
];
var ustep = 138 / 1024;
var vstep = 239 / 1024;
var uoffset = 60 / 1024;
var voffset = 26 / 1024;
var island_u_offset = -40 / 1024;
var island_v_offset = 20 / 1024;
var island = [
0,
0,
0,
0,
1,
0,
0,
1,
1,
0,
0,
0,
1,
1,
0,
0,
1,
1,
1,
0
// 15 - 19
];
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var current_indice = 0;
var face_vertex_pos = new Array(3);
var face_vertex_uv = new Array(3);
var v012;
for (v012 = 0; v012 < 3; v012++) {
face_vertex_pos[v012] = BABYLON2.Vector3.Zero();
face_vertex_uv[v012] = BABYLON2.Vector2.Zero();
}
for (var face = 0; face < 20; face++) {
for (v012 = 0; v012 < 3; v012++) {
var v_id = ico_indices[3 * face + v012];
face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
face_vertex_pos[v012].normalize().scaleInPlace(radius);
face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
}
var interp_vertex = function(i12, i22, c1, c2) {
var pos_x0 = BABYLON2.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i22 / subdivisions);
var pos_x1 = BABYLON2.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i22 / subdivisions);
var pos_interp = subdivisions === i22 ? face_vertex_pos[2] : BABYLON2.Vector3.Lerp(pos_x0, pos_x1, i12 / (subdivisions - i22));
pos_interp.normalize();
var vertex_normal;
if (flat) {
var centroid_x0 = BABYLON2.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
var centroid_x1 = BABYLON2.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
vertex_normal = BABYLON2.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
} else {
vertex_normal = new BABYLON2.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
}
vertex_normal.x /= radiusX;
vertex_normal.y /= radiusY;
vertex_normal.z /= radiusZ;
vertex_normal.normalize();
var uv_x0 = BABYLON2.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i22 / subdivisions);
var uv_x1 = BABYLON2.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i22 / subdivisions);
var uv_interp = subdivisions === i22 ? face_vertex_uv[2] : BABYLON2.Vector2.Lerp(uv_x0, uv_x1, i12 / (subdivisions - i22));
positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
uvs.push(uv_interp.x, uv_interp.y);
indices.push(current_indice);
current_indice++;
};
for (var i2 = 0; i2 < subdivisions; i2++) {
for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
interp_vertex(i1, i2, i1 + 1 / 3, i2 + 1 / 3);
interp_vertex(i1 + 1, i2, i1 + 1 / 3, i2 + 1 / 3);
interp_vertex(i1, i2 + 1, i1 + 1 / 3, i2 + 1 / 3);
if (i1 + i2 + 1 < subdivisions) {
interp_vertex(i1 + 1, i2, i1 + 2 / 3, i2 + 2 / 3);
interp_vertex(i1 + 1, i2 + 1, i1 + 2 / 3, i2 + 2 / 3);
interp_vertex(i1, i2 + 1, i1 + 2 / 3, i2 + 2 / 3);
}
}
}
}
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.CreatePolyhedron = function(options) {
var polyhedra = [];
polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
polyhedra[2] = {
vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
};
polyhedra[3] = {
vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
};
polyhedra[4] = {
vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
};
polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [4683e-6, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
polyhedra[14] = {
vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -4675e-6, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
};
var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
var size = options.size;
var sizeX = options.sizeX || size || 1;
var sizeY = options.sizeY || size || 1;
var sizeZ = options.sizeZ || size || 1;
var data2 = options.custom || polyhedra[type];
var nbfaces = data2.face.length;
var faceUV = options.faceUV || new Array(nbfaces);
var faceColors = options.faceColors;
var flat = options.flat === void 0 ? true : options.flat;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var positions = new Array();
var indices = new Array();
var normals = new Array();
var uvs = new Array();
var colors = new Array();
var index = 0;
var faceIdx = 0;
var indexes = new Array();
var i2 = 0;
var f = 0;
var u, v, ang, x, y, tmp;
if (flat) {
for (f = 0; f < nbfaces; f++) {
if (faceColors && faceColors[f] === void 0) {
faceColors[f] = new BABYLON2.Color4(1, 1, 1, 1);
}
if (faceUV && faceUV[f] === void 0) {
faceUV[f] = new BABYLON2.Vector4(0, 0, 1, 1);
}
}
}
if (!flat) {
for (i2 = 0; i2 < data2.vertex.length; i2++) {
positions.push(data2.vertex[i2][0] * sizeX, data2.vertex[i2][1] * sizeY, data2.vertex[i2][2] * sizeZ);
uvs.push(0, 0);
}
for (f = 0; f < nbfaces; f++) {
for (i2 = 0; i2 < data2.face[f].length - 2; i2++) {
indices.push(data2.face[f][0], data2.face[f][i2 + 2], data2.face[f][i2 + 1]);
}
}
} else {
for (f = 0; f < nbfaces; f++) {
var fl = data2.face[f].length;
ang = 2 * Math.PI / fl;
x = 0.5 * Math.tan(ang / 2);
y = 0.5;
for (i2 = 0; i2 < fl; i2++) {
positions.push(data2.vertex[data2.face[f][i2]][0] * sizeX, data2.vertex[data2.face[f][i2]][1] * sizeY, data2.vertex[data2.face[f][i2]][2] * sizeZ);
indexes.push(index);
index++;
u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
uvs.push(u, v);
tmp = x * Math.cos(ang) - y * Math.sin(ang);
y = x * Math.sin(ang) + y * Math.cos(ang);
x = tmp;
if (faceColors) {
colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
}
}
for (i2 = 0; i2 < fl - 2; i2++) {
indices.push(indexes[0 + faceIdx], indexes[i2 + 2 + faceIdx], indexes[i2 + 1 + faceIdx]);
}
faceIdx += fl;
}
}
VertexData2.ComputeNormals(positions, indices, normals);
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.positions = positions;
vertexData.indices = indices;
vertexData.normals = normals;
vertexData.uvs = uvs;
if (faceColors && flat) {
vertexData.colors = colors;
}
return vertexData;
};
VertexData2.CreateTorusKnot = function(options) {
var indices = new Array();
var positions = new Array();
var normals = new Array();
var uvs = new Array();
var radius = options.radius || 2;
var tube = options.tube || 0.5;
var radialSegments = options.radialSegments || 32;
var tubularSegments = options.tubularSegments || 32;
var p = options.p || 2;
var q = options.q || 3;
var sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
var getPos = function(angle) {
var cu = Math.cos(angle);
var su = Math.sin(angle);
var quOverP = q / p * angle;
var cs = Math.cos(quOverP);
var tx = radius * (2 + cs) * 0.5 * cu;
var ty = radius * (2 + cs) * su * 0.5;
var tz = radius * Math.sin(quOverP) * 0.5;
return new BABYLON2.Vector3(tx, ty, tz);
};
var i2;
var j;
for (i2 = 0; i2 <= radialSegments; i2++) {
var modI = i2 % radialSegments;
var u = modI / radialSegments * 2 * p * Math.PI;
var p1 = getPos(u);
var p2 = getPos(u + 0.01);
var tang = p2.subtract(p1);
var n = p2.add(p1);
var bitan = BABYLON2.Vector3.Cross(tang, n);
n = BABYLON2.Vector3.Cross(bitan, tang);
bitan.normalize();
n.normalize();
for (j = 0; j < tubularSegments; j++) {
var modJ = j % tubularSegments;
var v = modJ / tubularSegments * 2 * Math.PI;
var cx = -tube * Math.cos(v);
var cy = tube * Math.sin(v);
positions.push(p1.x + cx * n.x + cy * bitan.x);
positions.push(p1.y + cx * n.y + cy * bitan.y);
positions.push(p1.z + cx * n.z + cy * bitan.z);
uvs.push(i2 / radialSegments);
uvs.push(j / tubularSegments);
}
}
for (i2 = 0; i2 < radialSegments; i2++) {
for (j = 0; j < tubularSegments; j++) {
var jNext = (j + 1) % tubularSegments;
var a = i2 * tubularSegments + j;
var b2 = (i2 + 1) * tubularSegments + j;
var c = (i2 + 1) * tubularSegments + jNext;
var d = i2 * tubularSegments + jNext;
indices.push(d);
indices.push(b2);
indices.push(a);
indices.push(d);
indices.push(c);
indices.push(b2);
}
}
VertexData2.ComputeNormals(positions, indices, normals);
VertexData2._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
var vertexData = new VertexData2();
vertexData.indices = indices;
vertexData.positions = positions;
vertexData.normals = normals;
vertexData.uvs = uvs;
return vertexData;
};
VertexData2.ComputeNormals = function(positions, indices, normals, options) {
var index = 0;
var p1p2x = 0;
var p1p2y = 0;
var p1p2z = 0;
var p3p2x = 0;
var p3p2y = 0;
var p3p2z = 0;
var faceNormalx = 0;
var faceNormaly = 0;
var faceNormalz = 0;
var length = 0;
var v1x = 0;
var v1y = 0;
var v1z = 0;
var v2x = 0;
var v2y = 0;
var v2z = 0;
var v3x = 0;
var v3y = 0;
var v3z = 0;
var computeFacetNormals = false;
var computeFacetPositions = false;
var computeFacetPartitioning = false;
var computeDepthSort = false;
var faceNormalSign = 1;
var ratio = 0;
var distanceTo = null;
if (options) {
computeFacetNormals = options.facetNormals ? true : false;
computeFacetPositions = options.facetPositions ? true : false;
computeFacetPartitioning = options.facetPartitioning ? true : false;
faceNormalSign = options.useRightHandedSystem === true ? -1 : 1;
ratio = options.ratio || 0;
computeDepthSort = options.depthSort ? true : false;
distanceTo = options.distanceTo;
if (computeDepthSort) {
if (distanceTo === void 0) {
distanceTo = BABYLON2.Vector3.Zero();
}
var depthSortedFacets = options.depthSortedFacets;
}
}
var xSubRatio = 0;
var ySubRatio = 0;
var zSubRatio = 0;
var subSq = 0;
if (computeFacetPartitioning && options && options.bbSize) {
var ox = 0;
var oy = 0;
var oz = 0;
var b1x = 0;
var b1y = 0;
var b1z = 0;
var b2x = 0;
var b2y = 0;
var b2z = 0;
var b3x = 0;
var b3y = 0;
var b3z = 0;
var block_idx_o = 0;
var block_idx_v1 = 0;
var block_idx_v2 = 0;
var block_idx_v3 = 0;
var bbSizeMax = options.bbSize.x > options.bbSize.y ? options.bbSize.x : options.bbSize.y;
bbSizeMax = bbSizeMax > options.bbSize.z ? bbSizeMax : options.bbSize.z;
xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
subSq = options.subDiv.max * options.subDiv.max;
options.facetPartitioning.length = 0;
}
for (index = 0; index < positions.length; index++) {
normals[index] = 0;
}
var nbFaces = indices.length / 3 | 0;
for (index = 0; index < nbFaces; index++) {
v1x = indices[index * 3] * 3;
v1y = v1x + 1;
v1z = v1x + 2;
v2x = indices[index * 3 + 1] * 3;
v2y = v2x + 1;
v2z = v2x + 2;
v3x = indices[index * 3 + 2] * 3;
v3y = v3x + 1;
v3z = v3x + 2;
p1p2x = positions[v1x] - positions[v2x];
p1p2y = positions[v1y] - positions[v2y];
p1p2z = positions[v1z] - positions[v2z];
p3p2x = positions[v3x] - positions[v2x];
p3p2y = positions[v3y] - positions[v2y];
p3p2z = positions[v3z] - positions[v2z];
faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
length = length === 0 ? 1 : length;
faceNormalx /= length;
faceNormaly /= length;
faceNormalz /= length;
if (computeFacetNormals && options) {
options.facetNormals[index].x = faceNormalx;
options.facetNormals[index].y = faceNormaly;
options.facetNormals[index].z = faceNormalz;
}
if (computeFacetPositions && options) {
options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3;
options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3;
options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3;
}
if (computeFacetPartitioning && options) {
ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
options.facetPartitioning[block_idx_v1].push(index);
if (block_idx_v2 != block_idx_v1) {
options.facetPartitioning[block_idx_v2].push(index);
}
if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
options.facetPartitioning[block_idx_v3].push(index);
}
if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
options.facetPartitioning[block_idx_o].push(index);
}
}
if (computeDepthSort && options && options.facetPositions) {
var dsf = depthSortedFacets[index];
dsf.ind = index * 3;
dsf.sqDistance = BABYLON2.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
}
normals[v1x] += faceNormalx;
normals[v1y] += faceNormaly;
normals[v1z] += faceNormalz;
normals[v2x] += faceNormalx;
normals[v2y] += faceNormaly;
normals[v2z] += faceNormalz;
normals[v3x] += faceNormalx;
normals[v3y] += faceNormaly;
normals[v3z] += faceNormalz;
}
for (index = 0; index < normals.length / 3; index++) {
faceNormalx = normals[index * 3];
faceNormaly = normals[index * 3 + 1];
faceNormalz = normals[index * 3 + 2];
length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
length = length === 0 ? 1 : length;
faceNormalx /= length;
faceNormaly /= length;
faceNormalz /= length;
normals[index * 3] = faceNormalx;
normals[index * 3 + 1] = faceNormaly;
normals[index * 3 + 2] = faceNormalz;
}
};
VertexData2._ComputeSides = function(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
var li = indices.length;
var ln = normals.length;
var i2;
var n;
sideOrientation = sideOrientation || BABYLON2.Mesh.DEFAULTSIDE;
switch (sideOrientation) {
case BABYLON2.Mesh.FRONTSIDE:
break;
case BABYLON2.Mesh.BACKSIDE:
var tmp;
for (i2 = 0; i2 < li; i2 += 3) {
tmp = indices[i2];
indices[i2] = indices[i2 + 2];
indices[i2 + 2] = tmp;
}
for (n = 0; n < ln; n++) {
normals[n] = -normals[n];
}
break;
case BABYLON2.Mesh.DOUBLESIDE:
var lp = positions.length;
var l = lp / 3;
for (var p = 0; p < lp; p++) {
positions[lp + p] = positions[p];
}
for (i2 = 0; i2 < li; i2 += 3) {
indices[i2 + li] = indices[i2 + 2] + l;
indices[i2 + 1 + li] = indices[i2 + 1] + l;
indices[i2 + 2 + li] = indices[i2] + l;
}
for (n = 0; n < ln; n++) {
normals[ln + n] = -normals[n];
}
var lu = uvs.length;
var u = 0;
for (u = 0; u < lu; u++) {
uvs[u + lu] = uvs[u];
}
frontUVs = frontUVs ? frontUVs : new BABYLON2.Vector4(0, 0, 1, 1);
backUVs = backUVs ? backUVs : new BABYLON2.Vector4(0, 0, 1, 1);
u = 0;
for (i2 = 0; i2 < lu / 2; i2++) {
uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
u += 2;
}
break;
}
};
VertexData2.ImportVertexData = function(parsedVertexData, geometry) {
var vertexData = new VertexData2();
var positions = parsedVertexData.positions;
if (positions) {
vertexData.set(positions, BABYLON2.VertexBuffer.PositionKind);
}
var normals = parsedVertexData.normals;
if (normals) {
vertexData.set(normals, BABYLON2.VertexBuffer.NormalKind);
}
var tangents = parsedVertexData.tangents;
if (tangents) {
vertexData.set(tangents, BABYLON2.VertexBuffer.TangentKind);
}
var uvs = parsedVertexData.uvs;
if (uvs) {
vertexData.set(uvs, BABYLON2.VertexBuffer.UVKind);
}
var uv2s = parsedVertexData.uv2s;
if (uv2s) {
vertexData.set(uv2s, BABYLON2.VertexBuffer.UV2Kind);
}
var uv3s = parsedVertexData.uv3s;
if (uv3s) {
vertexData.set(uv3s, BABYLON2.VertexBuffer.UV3Kind);
}
var uv4s = parsedVertexData.uv4s;
if (uv4s) {
vertexData.set(uv4s, BABYLON2.VertexBuffer.UV4Kind);
}
var uv5s = parsedVertexData.uv5s;
if (uv5s) {
vertexData.set(uv5s, BABYLON2.VertexBuffer.UV5Kind);
}
var uv6s = parsedVertexData.uv6s;
if (uv6s) {
vertexData.set(uv6s, BABYLON2.VertexBuffer.UV6Kind);
}
var colors = parsedVertexData.colors;
if (colors) {
vertexData.set(BABYLON2.Color4.CheckColors4(colors, positions.length / 3), BABYLON2.VertexBuffer.ColorKind);
}
var matricesIndices = parsedVertexData.matricesIndices;
if (matricesIndices) {
vertexData.set(matricesIndices, BABYLON2.VertexBuffer.MatricesIndicesKind);
}
var matricesWeights = parsedVertexData.matricesWeights;
if (matricesWeights) {
vertexData.set(matricesWeights, BABYLON2.VertexBuffer.MatricesWeightsKind);
}
var indices = parsedVertexData.indices;
if (indices) {
vertexData.indices = indices;
}
geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
};
return VertexData2;
}()
);
BABYLON2.VertexData = VertexData;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Geometry = (
/** @class */
function() {
function Geometry2(id, scene, vertexData, updatable, mesh2) {
if (updatable === void 0) {
updatable = false;
}
if (mesh2 === void 0) {
mesh2 = null;
}
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NONE;
this._totalVertices = 0;
this._isDisposed = false;
this._indexBufferIsUpdatable = false;
this.id = id;
this._engine = scene.getEngine();
this._meshes = [];
this._scene = scene;
this._vertexBuffers = {};
this._indices = [];
this._updatable = updatable;
if (vertexData) {
this.setAllVerticesData(vertexData, updatable);
} else {
this._totalVertices = 0;
this._indices = [];
}
if (this._engine.getCaps().vertexArrayObject) {
this._vertexArrayObjects = {};
}
if (mesh2) {
if (mesh2.getClassName() === "LinesMesh") {
this.boundingBias = new BABYLON2.Vector2(0, mesh2.intersectionThreshold);
this._updateExtend();
}
this.applyToMesh(mesh2);
mesh2.computeWorldMatrix(true);
}
}
Object.defineProperty(Geometry2.prototype, "boundingBias", {
/**
* Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
*/
get: function() {
return this._boundingBias;
},
/**
* Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
*/
set: function(value) {
if (this._boundingBias) {
if (this._boundingBias.equals(value)) {
return;
}
this._boundingBias.copyFrom(value);
} else {
this._boundingBias = value.clone();
}
this._updateBoundingInfo(true, null);
},
enumerable: true,
configurable: true
});
Geometry2.CreateGeometryForMesh = function(mesh2) {
var geometry = new Geometry2(Geometry2.RandomId(), mesh2.getScene());
geometry.applyToMesh(mesh2);
return geometry;
};
Object.defineProperty(Geometry2.prototype, "extend", {
/**
* Gets the current extend of the geometry
*/
get: function() {
return this._extend;
},
enumerable: true,
configurable: true
});
Geometry2.prototype.getScene = function() {
return this._scene;
};
Geometry2.prototype.getEngine = function() {
return this._engine;
};
Geometry2.prototype.isReady = function() {
return this.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_NONE;
};
Object.defineProperty(Geometry2.prototype, "doNotSerialize", {
/**
* Gets a value indicating that the geometry should not be serialized
*/
get: function() {
for (var index = 0; index < this._meshes.length; index++) {
if (!this._meshes[index].doNotSerialize) {
return false;
}
}
return true;
},
enumerable: true,
configurable: true
});
Geometry2.prototype._rebuild = function() {
if (this._vertexArrayObjects) {
this._vertexArrayObjects = {};
}
if (this._meshes.length !== 0 && this._indices) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices);
}
for (var key in this._vertexBuffers) {
var vertexBuffer = this._vertexBuffers[key];
vertexBuffer._rebuild();
}
};
Geometry2.prototype.setAllVerticesData = function(vertexData, updatable) {
vertexData.applyToGeometry(this, updatable);
this.notifyUpdate();
};
Geometry2.prototype.setVerticesData = function(kind, data2, updatable, stride) {
if (updatable === void 0) {
updatable = false;
}
var buffer = new BABYLON2.VertexBuffer(this._engine, data2, kind, updatable, this._meshes.length === 0, stride);
this.setVerticesBuffer(buffer);
};
Geometry2.prototype.removeVerticesData = function(kind) {
if (this._vertexBuffers[kind]) {
this._vertexBuffers[kind].dispose();
delete this._vertexBuffers[kind];
}
};
Geometry2.prototype.setVerticesBuffer = function(buffer, totalVertices) {
if (totalVertices === void 0) {
totalVertices = null;
}
var kind = buffer.getKind();
if (this._vertexBuffers[kind]) {
this._vertexBuffers[kind].dispose();
}
this._vertexBuffers[kind] = buffer;
if (kind === BABYLON2.VertexBuffer.PositionKind) {
var data2 = buffer.getData();
if (totalVertices != null) {
this._totalVertices = totalVertices;
} else {
if (data2 != null) {
this._totalVertices = data2.length / (buffer.byteStride / 4);
}
}
this._updateExtend(data2);
this._resetPointsArrayCache();
var meshes = this._meshes;
var numOfMeshes = meshes.length;
for (var index = 0; index < numOfMeshes; index++) {
var mesh2 = meshes[index];
mesh2._boundingInfo = new BABYLON2.BoundingInfo(this._extend.minimum, this._extend.maximum);
mesh2._createGlobalSubMesh(false);
mesh2.computeWorldMatrix(true);
}
}
this.notifyUpdate(kind);
if (this._vertexArrayObjects) {
this._disposeVertexArrayObjects();
this._vertexArrayObjects = {};
}
};
Geometry2.prototype.updateVerticesDataDirectly = function(kind, data2, offset, useBytes) {
if (useBytes === void 0) {
useBytes = false;
}
var vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return;
}
vertexBuffer.updateDirectly(data2, offset, useBytes);
this.notifyUpdate(kind);
};
Geometry2.prototype.updateVerticesData = function(kind, data2, updateExtends) {
if (updateExtends === void 0) {
updateExtends = false;
}
var vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return;
}
vertexBuffer.update(data2);
if (kind === BABYLON2.VertexBuffer.PositionKind) {
this._updateBoundingInfo(updateExtends, data2);
}
this.notifyUpdate(kind);
};
Geometry2.prototype._updateBoundingInfo = function(updateExtends, data2) {
if (updateExtends) {
this._updateExtend(data2);
}
var meshes = this._meshes;
var numOfMeshes = meshes.length;
this._resetPointsArrayCache();
for (var index = 0; index < numOfMeshes; index++) {
var mesh2 = meshes[index];
if (updateExtends) {
mesh2._boundingInfo = new BABYLON2.BoundingInfo(this._extend.minimum, this._extend.maximum);
for (var subIndex = 0; subIndex < mesh2.subMeshes.length; subIndex++) {
var subMesh = mesh2.subMeshes[subIndex];
subMesh.refreshBoundingInfo();
}
}
}
};
Geometry2.prototype._bind = function(effect, indexToBind) {
if (!effect) {
return;
}
if (indexToBind === void 0) {
indexToBind = this._indexBuffer;
}
var vbs = this.getVertexBuffers();
if (!vbs) {
return;
}
if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
this._engine.bindBuffers(vbs, indexToBind, effect);
return;
}
if (!this._vertexArrayObjects[effect.key]) {
this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
}
this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
};
Geometry2.prototype.getTotalVertices = function() {
if (!this.isReady()) {
return 0;
}
return this._totalVertices;
};
Geometry2.prototype.getVerticesData = function(kind, copyWhenShared, forceCopy) {
var vertexBuffer = this.getVertexBuffer(kind);
if (!vertexBuffer) {
return null;
}
var data2 = vertexBuffer.getData();
if (!data2) {
return null;
}
var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON2.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
var count = this._totalVertices * vertexBuffer.getSize();
if (vertexBuffer.type !== BABYLON2.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
var copy_1 = new Array(count);
vertexBuffer.forEach(count, function(value, index) {
copy_1[index] = value;
});
return copy_1;
}
if (!(data2 instanceof Array || data2 instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data2.length !== count) {
if (data2 instanceof Array) {
var offset = vertexBuffer.byteOffset / 4;
return BABYLON2.Tools.Slice(data2, offset, offset + count);
} else if (data2 instanceof ArrayBuffer) {
return new Float32Array(data2, vertexBuffer.byteOffset, count);
} else {
var offset = data2.byteOffset + vertexBuffer.byteOffset;
if (forceCopy || copyWhenShared && this._meshes.length !== 1) {
var result = new Float32Array(count);
var source = new Float32Array(data2.buffer, offset, count);
result.set(source);
return result;
}
return new Float32Array(data2.buffer, offset, Math.min(count, data2.buffer.byteLength / 4));
}
}
if (forceCopy || copyWhenShared && this._meshes.length !== 1) {
return BABYLON2.Tools.Slice(data2);
}
return data2;
};
Geometry2.prototype.isVertexBufferUpdatable = function(kind) {
var vb = this._vertexBuffers[kind];
if (!vb) {
return false;
}
return vb.isUpdatable();
};
Geometry2.prototype.getVertexBuffer = function(kind) {
if (!this.isReady()) {
return null;
}
return this._vertexBuffers[kind];
};
Geometry2.prototype.getVertexBuffers = function() {
if (!this.isReady()) {
return null;
}
return this._vertexBuffers;
};
Geometry2.prototype.isVerticesDataPresent = function(kind) {
if (!this._vertexBuffers) {
if (this._delayInfo) {
return this._delayInfo.indexOf(kind) !== -1;
}
return false;
}
return this._vertexBuffers[kind] !== void 0;
};
Geometry2.prototype.getVerticesDataKinds = function() {
var result = [];
var kind;
if (!this._vertexBuffers && this._delayInfo) {
for (kind in this._delayInfo) {
result.push(kind);
}
} else {
for (kind in this._vertexBuffers) {
result.push(kind);
}
}
return result;
};
Geometry2.prototype.updateIndices = function(indices, offset) {
if (!this._indexBuffer) {
return;
}
if (!this._indexBufferIsUpdatable) {
this.setIndices(indices, null, true);
} else {
this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
}
};
Geometry2.prototype.setIndices = function(indices, totalVertices, updatable) {
if (totalVertices === void 0) {
totalVertices = null;
}
if (updatable === void 0) {
updatable = false;
}
if (this._indexBuffer) {
this._engine._releaseBuffer(this._indexBuffer);
}
this._disposeVertexArrayObjects();
this._indices = indices;
this._indexBufferIsUpdatable = updatable;
if (this._meshes.length !== 0 && this._indices) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
}
if (totalVertices != void 0) {
this._totalVertices = totalVertices;
}
var meshes = this._meshes;
var numOfMeshes = meshes.length;
for (var index = 0; index < numOfMeshes; index++) {
meshes[index]._createGlobalSubMesh(true);
}
this.notifyUpdate();
};
Geometry2.prototype.getTotalIndices = function() {
if (!this.isReady()) {
return 0;
}
return this._indices.length;
};
Geometry2.prototype.getIndices = function(copyWhenShared, forceCopy) {
if (!this.isReady()) {
return null;
}
var orig = this._indices;
if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
return orig;
} else {
var len = orig.length;
var copy = [];
for (var i2 = 0; i2 < len; i2++) {
copy.push(orig[i2]);
}
return copy;
}
};
Geometry2.prototype.getIndexBuffer = function() {
if (!this.isReady()) {
return null;
}
return this._indexBuffer;
};
Geometry2.prototype._releaseVertexArrayObject = function(effect) {
if (effect === void 0) {
effect = null;
}
if (!effect || !this._vertexArrayObjects) {
return;
}
if (this._vertexArrayObjects[effect.key]) {
this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
delete this._vertexArrayObjects[effect.key];
}
};
Geometry2.prototype.releaseForMesh = function(mesh2, shouldDispose) {
var meshes = this._meshes;
var index = meshes.indexOf(mesh2);
if (index === -1) {
return;
}
meshes.splice(index, 1);
mesh2._geometry = null;
if (meshes.length === 0 && shouldDispose) {
this.dispose();
}
};
Geometry2.prototype.applyToMesh = function(mesh2) {
if (mesh2._geometry === this) {
return;
}
var previousGeometry = mesh2._geometry;
if (previousGeometry) {
previousGeometry.releaseForMesh(mesh2);
}
var meshes = this._meshes;
mesh2._geometry = this;
this._scene.pushGeometry(this);
meshes.push(mesh2);
if (this.isReady()) {
this._applyToMesh(mesh2);
} else {
mesh2._boundingInfo = this._boundingInfo;
}
};
Geometry2.prototype._updateExtend = function(data2) {
if (data2 === void 0) {
data2 = null;
}
if (!data2) {
data2 = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
}
this._extend = BABYLON2.Tools.ExtractMinAndMax(data2, 0, this._totalVertices, this.boundingBias, 3);
};
Geometry2.prototype._applyToMesh = function(mesh2) {
var numOfMeshes = this._meshes.length;
for (var kind in this._vertexBuffers) {
if (numOfMeshes === 1) {
this._vertexBuffers[kind].create();
}
var buffer = this._vertexBuffers[kind].getBuffer();
if (buffer) {
buffer.references = numOfMeshes;
}
if (kind === BABYLON2.VertexBuffer.PositionKind) {
if (!this._extend) {
this._updateExtend();
}
mesh2._boundingInfo = new BABYLON2.BoundingInfo(this._extend.minimum, this._extend.maximum);
mesh2._createGlobalSubMesh(false);
mesh2._updateBoundingInfo();
}
}
if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
this._indexBuffer = this._engine.createIndexBuffer(this._indices);
}
if (this._indexBuffer) {
this._indexBuffer.references = numOfMeshes;
}
mesh2._syncGeometryWithMorphTargetManager();
};
Geometry2.prototype.notifyUpdate = function(kind) {
if (this.onGeometryUpdated) {
this.onGeometryUpdated(this, kind);
}
for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
mesh2._markSubMeshesAsAttributesDirty();
}
};
Geometry2.prototype.load = function(scene, onLoaded) {
if (this.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_LOADING) {
return;
}
if (this.isReady()) {
if (onLoaded) {
onLoaded();
}
return;
}
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADING;
this._queueLoad(scene, onLoaded);
};
Geometry2.prototype._queueLoad = function(scene, onLoaded) {
var _this = this;
if (!this.delayLoadingFile) {
return;
}
scene._addPendingData(this);
scene._loadFile(this.delayLoadingFile, function(data2) {
if (!_this._delayLoadingFunction) {
return;
}
_this._delayLoadingFunction(JSON.parse(data2), _this);
_this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADED;
_this._delayInfo = [];
scene._removePendingData(_this);
var meshes = _this._meshes;
var numOfMeshes = meshes.length;
for (var index = 0; index < numOfMeshes; index++) {
_this._applyToMesh(meshes[index]);
}
if (onLoaded) {
onLoaded();
}
}, void 0, true);
};
Geometry2.prototype.toLeftHanded = function() {
var tIndices = this.getIndices(false);
if (tIndices != null && tIndices.length > 0) {
for (var i2 = 0; i2 < tIndices.length; i2 += 3) {
var tTemp = tIndices[i2 + 0];
tIndices[i2 + 0] = tIndices[i2 + 2];
tIndices[i2 + 2] = tTemp;
}
this.setIndices(tIndices);
}
var tPositions = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind, false);
if (tPositions != null && tPositions.length > 0) {
for (var i2 = 0; i2 < tPositions.length; i2 += 3) {
tPositions[i2 + 2] = -tPositions[i2 + 2];
}
this.setVerticesData(BABYLON2.VertexBuffer.PositionKind, tPositions, false);
}
var tNormals = this.getVerticesData(BABYLON2.VertexBuffer.NormalKind, false);
if (tNormals != null && tNormals.length > 0) {
for (var i2 = 0; i2 < tNormals.length; i2 += 3) {
tNormals[i2 + 2] = -tNormals[i2 + 2];
}
this.setVerticesData(BABYLON2.VertexBuffer.NormalKind, tNormals, false);
}
};
Geometry2.prototype._resetPointsArrayCache = function() {
this._positions = null;
};
Geometry2.prototype._generatePointsArray = function() {
if (this._positions) {
return true;
}
var data2 = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (!data2 || data2.length === 0) {
return false;
}
this._positions = [];
for (var index = 0; index < data2.length; index += 3) {
this._positions.push(BABYLON2.Vector3.FromArray(data2, index));
}
return true;
};
Geometry2.prototype.isDisposed = function() {
return this._isDisposed;
};
Geometry2.prototype._disposeVertexArrayObjects = function() {
if (this._vertexArrayObjects) {
for (var kind in this._vertexArrayObjects) {
this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
}
this._vertexArrayObjects = {};
}
};
Geometry2.prototype.dispose = function() {
var meshes = this._meshes;
var numOfMeshes = meshes.length;
var index;
for (index = 0; index < numOfMeshes; index++) {
this.releaseForMesh(meshes[index]);
}
this._meshes = [];
this._disposeVertexArrayObjects();
for (var kind in this._vertexBuffers) {
this._vertexBuffers[kind].dispose();
}
this._vertexBuffers = {};
this._totalVertices = 0;
if (this._indexBuffer) {
this._engine._releaseBuffer(this._indexBuffer);
}
this._indexBuffer = null;
this._indices = [];
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NONE;
this.delayLoadingFile = null;
this._delayLoadingFunction = null;
this._delayInfo = [];
this._boundingInfo = null;
this._scene.removeGeometry(this);
this._isDisposed = true;
};
Geometry2.prototype.copy = function(id) {
var vertexData = new BABYLON2.VertexData();
vertexData.indices = [];
var indices = this.getIndices();
if (indices) {
for (var index = 0; index < indices.length; index++) {
vertexData.indices.push(indices[index]);
}
}
var updatable = false;
var stopChecking = false;
var kind;
for (kind in this._vertexBuffers) {
var data2 = this.getVerticesData(kind);
if (data2 instanceof Float32Array) {
vertexData.set(new Float32Array(data2), kind);
} else {
vertexData.set(data2.slice(0), kind);
}
if (!stopChecking) {
var vb = this.getVertexBuffer(kind);
if (vb) {
updatable = vb.isUpdatable();
stopChecking = !updatable;
}
}
}
var geometry = new Geometry2(id, this._scene, vertexData, updatable);
geometry.delayLoadState = this.delayLoadState;
geometry.delayLoadingFile = this.delayLoadingFile;
geometry._delayLoadingFunction = this._delayLoadingFunction;
for (kind in this._delayInfo) {
geometry._delayInfo = geometry._delayInfo || [];
geometry._delayInfo.push(kind);
}
geometry._boundingInfo = new BABYLON2.BoundingInfo(this._extend.minimum, this._extend.maximum);
return geometry;
};
Geometry2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.id = this.id;
serializationObject.updatable = this._updatable;
if (BABYLON2.Tags && BABYLON2.Tags.HasTags(this)) {
serializationObject.tags = BABYLON2.Tags.GetTags(this);
}
return serializationObject;
};
Geometry2.prototype.toNumberArray = function(origin) {
if (Array.isArray(origin)) {
return origin;
} else {
return Array.prototype.slice.call(origin);
}
};
Geometry2.prototype.serializeVerticeData = function() {
var serializationObject = this.serialize();
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.PositionKind)) {
serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.PositionKind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.PositionKind)) {
serializationObject.positions._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.NormalKind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.NormalKind)) {
serializationObject.normals._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.TangentKind)) {
serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.TangentKind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.TangentKind)) {
serializationObject.tangets._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.UVKind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.UVKind)) {
serializationObject.uvs._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind)) {
serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.UV2Kind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.UV2Kind)) {
serializationObject.uv2s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.UV3Kind)) {
serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.UV3Kind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.UV3Kind)) {
serializationObject.uv3s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.UV4Kind)) {
serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.UV4Kind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.UV4Kind)) {
serializationObject.uv4s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.UV5Kind)) {
serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.UV5Kind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.UV5Kind)) {
serializationObject.uv5s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.UV6Kind)) {
serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.UV6Kind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.UV6Kind)) {
serializationObject.uv6s._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.ColorKind)) {
serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.ColorKind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.ColorKind)) {
serializationObject.colors._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesIndicesKind)) {
serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind));
serializationObject.matricesIndices._isExpanded = true;
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.MatricesIndicesKind)) {
serializationObject.matricesIndices._updatable = true;
}
}
if (this.isVerticesDataPresent(BABYLON2.VertexBuffer.MatricesWeightsKind)) {
serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind));
if (this.isVertexBufferUpdatable(BABYLON2.VertexBuffer.MatricesWeightsKind)) {
serializationObject.matricesWeights._updatable = true;
}
}
serializationObject.indices = this.toNumberArray(this.getIndices());
return serializationObject;
};
Geometry2.ExtractFromMesh = function(mesh2, id) {
var geometry = mesh2._geometry;
if (!geometry) {
return null;
}
return geometry.copy(id);
};
Geometry2.RandomId = function() {
return BABYLON2.Tools.RandomId();
};
Geometry2._ImportGeometry = function(parsedGeometry, mesh2) {
var scene = mesh2.getScene();
var geometryId = parsedGeometry.geometryId;
if (geometryId) {
var geometry = scene.getGeometryByID(geometryId);
if (geometry) {
geometry.applyToMesh(mesh2);
}
} else if (parsedGeometry instanceof ArrayBuffer) {
var binaryInfo = mesh2._binaryInfo;
if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.PositionKind, positionsData, false);
}
if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.NormalKind, normalsData, false);
}
if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.TangentKind, tangentsData, false);
}
if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.UVKind, uvsData, false);
}
if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV2Kind, uvs2Data, false);
}
if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV3Kind, uvs3Data, false);
}
if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV4Kind, uvs4Data, false);
}
if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV5Kind, uvs5Data, false);
}
if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV6Kind, uvs6Data, false);
}
if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
}
if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
var floatIndices = [];
for (var i2 = 0; i2 < matricesIndicesData.length; i2++) {
var index = matricesIndicesData[i2];
floatIndices.push(index & 255);
floatIndices.push((index & 65280) >> 8);
floatIndices.push((index & 16711680) >> 16);
floatIndices.push(index >> 24);
}
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind, floatIndices, false);
}
if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
}
if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
mesh2.setIndices(indicesData, null);
}
if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
mesh2.subMeshes = [];
for (var i2 = 0; i2 < binaryInfo.subMeshesAttrDesc.count; i2++) {
var materialIndex = subMeshesData[i2 * 5 + 0];
var verticesStart = subMeshesData[i2 * 5 + 1];
var verticesCount = subMeshesData[i2 * 5 + 2];
var indexStart = subMeshesData[i2 * 5 + 3];
var indexCount = subMeshesData[i2 * 5 + 4];
BABYLON2.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh2);
}
}
} else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
mesh2.setVerticesData(BABYLON2.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
if (parsedGeometry.tangents) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
}
if (parsedGeometry.uvs) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
}
if (parsedGeometry.uvs2) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
}
if (parsedGeometry.uvs3) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
}
if (parsedGeometry.uvs4) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
}
if (parsedGeometry.uvs5) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
}
if (parsedGeometry.uvs6) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
}
if (parsedGeometry.colors) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.ColorKind, BABYLON2.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
}
if (parsedGeometry.matricesIndices) {
if (!parsedGeometry.matricesIndices._isExpanded) {
var floatIndices = [];
for (var i2 = 0; i2 < parsedGeometry.matricesIndices.length; i2++) {
var matricesIndex = parsedGeometry.matricesIndices[i2];
floatIndices.push(matricesIndex & 255);
floatIndices.push((matricesIndex & 65280) >> 8);
floatIndices.push((matricesIndex & 16711680) >> 16);
floatIndices.push(matricesIndex >> 24);
}
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
} else {
delete parsedGeometry.matricesIndices._isExpanded;
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
}
}
if (parsedGeometry.matricesIndicesExtra) {
if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
var floatIndices = [];
for (var i2 = 0; i2 < parsedGeometry.matricesIndicesExtra.length; i2++) {
var matricesIndex = parsedGeometry.matricesIndicesExtra[i2];
floatIndices.push(matricesIndex & 255);
floatIndices.push((matricesIndex & 65280) >> 8);
floatIndices.push((matricesIndex & 16711680) >> 16);
floatIndices.push(matricesIndex >> 24);
}
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
} else {
delete parsedGeometry.matricesIndices._isExpanded;
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
}
}
if (parsedGeometry.matricesWeights) {
Geometry2._CleanMatricesWeights(parsedGeometry, mesh2);
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
}
if (parsedGeometry.matricesWeightsExtra) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
}
mesh2.setIndices(parsedGeometry.indices, null);
}
if (parsedGeometry.subMeshes) {
mesh2.subMeshes = [];
for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
BABYLON2.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh2);
}
}
if (mesh2._shouldGenerateFlatShading) {
mesh2.convertToFlatShadedMesh();
delete mesh2._shouldGenerateFlatShading;
}
mesh2.computeWorldMatrix(true);
scene.onMeshImportedObservable.notifyObservers(mesh2);
};
Geometry2._CleanMatricesWeights = function(parsedGeometry, mesh2) {
var epsilon = 1e-3;
if (!BABYLON2.SceneLoader.CleanBoneMatrixWeights) {
return;
}
var noInfluenceBoneIndex = 0;
if (parsedGeometry.skeletonId > -1) {
var skeleton = mesh2.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
if (!skeleton) {
return;
}
noInfluenceBoneIndex = skeleton.bones.length;
} else {
return;
}
var matricesIndices = mesh2.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind);
var matricesIndicesExtra = mesh2.getVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
var matricesWeights = parsedGeometry.matricesWeights;
var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
var influencers = parsedGeometry.numBoneInfluencer;
var size = matricesWeights.length;
for (var i2 = 0; i2 < size; i2 += 4) {
var weight = 0;
var firstZeroWeight = -1;
for (var j = 0; j < 4; j++) {
var w = matricesWeights[i2 + j];
weight += w;
if (w < epsilon && firstZeroWeight < 0) {
firstZeroWeight = j;
}
}
if (matricesWeightsExtra) {
for (var j = 0; j < 4; j++) {
var w = matricesWeightsExtra[i2 + j];
weight += w;
if (w < epsilon && firstZeroWeight < 0) {
firstZeroWeight = j + 4;
}
}
}
if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) {
firstZeroWeight = influencers - 1;
}
if (weight > epsilon) {
var mweight = 1 / weight;
for (var j = 0; j < 4; j++) {
matricesWeights[i2 + j] *= mweight;
}
if (matricesWeightsExtra) {
for (var j = 0; j < 4; j++) {
matricesWeightsExtra[i2 + j] *= mweight;
}
}
} else {
if (firstZeroWeight >= 4) {
matricesWeightsExtra[i2 + firstZeroWeight - 4] = 1 - weight;
matricesIndicesExtra[i2 + firstZeroWeight - 4] = noInfluenceBoneIndex;
} else {
matricesWeights[i2 + firstZeroWeight] = 1 - weight;
matricesIndices[i2 + firstZeroWeight] = noInfluenceBoneIndex;
}
}
}
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesKind, matricesIndices);
if (parsedGeometry.matricesWeightsExtra) {
mesh2.setVerticesData(BABYLON2.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
}
};
Geometry2.Parse = function(parsedVertexData, scene, rootUrl) {
if (scene.getGeometryByID(parsedVertexData.id)) {
return null;
}
var geometry = new Geometry2(parsedVertexData.id, scene, void 0, parsedVertexData.updatable);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(geometry, parsedVertexData.tags);
}
if (parsedVertexData.delayLoadingFile) {
geometry.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED;
geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
geometry._boundingInfo = new BABYLON2.BoundingInfo(BABYLON2.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON2.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
geometry._delayInfo = [];
if (parsedVertexData.hasUVs) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.UVKind);
}
if (parsedVertexData.hasUVs2) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.UV2Kind);
}
if (parsedVertexData.hasUVs3) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.UV3Kind);
}
if (parsedVertexData.hasUVs4) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.UV4Kind);
}
if (parsedVertexData.hasUVs5) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.UV5Kind);
}
if (parsedVertexData.hasUVs6) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.UV6Kind);
}
if (parsedVertexData.hasColors) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.ColorKind);
}
if (parsedVertexData.hasMatricesIndices) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
}
if (parsedVertexData.hasMatricesWeights) {
geometry._delayInfo.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
}
geometry._delayLoadingFunction = BABYLON2.VertexData.ImportVertexData;
} else {
BABYLON2.VertexData.ImportVertexData(parsedVertexData, geometry);
}
scene.pushGeometry(geometry, true);
return geometry;
};
return Geometry2;
}()
);
BABYLON2.Geometry = Geometry;
var _PrimitiveGeometry = (
/** @class */
function(_super) {
__extends(_PrimitiveGeometry2, _super);
function _PrimitiveGeometry2(id, scene, _canBeRegenerated, mesh2) {
if (_canBeRegenerated === void 0) {
_canBeRegenerated = false;
}
if (mesh2 === void 0) {
mesh2 = null;
}
var _this = _super.call(this, id, scene, void 0, false, mesh2) || this;
_this._canBeRegenerated = _canBeRegenerated;
_this._beingRegenerated = true;
_this.regenerate();
_this._beingRegenerated = false;
return _this;
}
_PrimitiveGeometry2.prototype.canBeRegenerated = function() {
return this._canBeRegenerated;
};
_PrimitiveGeometry2.prototype.regenerate = function() {
if (!this._canBeRegenerated) {
return;
}
this._beingRegenerated = true;
this.setAllVerticesData(this._regenerateVertexData(), false);
this._beingRegenerated = false;
};
_PrimitiveGeometry2.prototype.asNewGeometry = function(id) {
return _super.prototype.copy.call(this, id);
};
_PrimitiveGeometry2.prototype.setAllVerticesData = function(vertexData, updatable) {
if (!this._beingRegenerated) {
return;
}
_super.prototype.setAllVerticesData.call(this, vertexData, false);
};
_PrimitiveGeometry2.prototype.setVerticesData = function(kind, data2, updatable) {
if (!this._beingRegenerated) {
return;
}
_super.prototype.setVerticesData.call(this, kind, data2, false);
};
_PrimitiveGeometry2.prototype._regenerateVertexData = function() {
throw new Error("Abstract method");
};
_PrimitiveGeometry2.prototype.copy = function(id) {
throw new Error("Must be overriden in sub-classes.");
};
_PrimitiveGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.canBeRegenerated = this.canBeRegenerated();
return serializationObject;
};
return _PrimitiveGeometry2;
}(Geometry)
);
BABYLON2._PrimitiveGeometry = _PrimitiveGeometry;
var RibbonGeometry = (
/** @class */
function(_super) {
__extends(RibbonGeometry2, _super);
function RibbonGeometry2(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh2, side) {
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.pathArray = pathArray;
_this.closeArray = closeArray;
_this.closePath = closePath;
_this.offset = offset;
_this.side = side;
return _this;
}
RibbonGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
};
RibbonGeometry2.prototype.copy = function(id) {
return new RibbonGeometry2(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), void 0, this.side);
};
return RibbonGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.RibbonGeometry = RibbonGeometry;
var BoxGeometry = (
/** @class */
function(_super) {
__extends(BoxGeometry2, _super);
function BoxGeometry2(id, scene, size, canBeRegenerated, mesh2, side) {
if (mesh2 === void 0) {
mesh2 = null;
}
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.size = size;
_this.side = side;
return _this;
}
BoxGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
};
BoxGeometry2.prototype.copy = function(id) {
return new BoxGeometry2(id, this.getScene(), this.size, this.canBeRegenerated(), void 0, this.side);
};
BoxGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.size = this.size;
return serializationObject;
};
BoxGeometry2.Parse = function(parsedBox, scene) {
if (scene.getGeometryByID(parsedBox.id)) {
return null;
}
var box = new BoxGeometry2(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(box, parsedBox.tags);
}
scene.pushGeometry(box, true);
return box;
};
return BoxGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.BoxGeometry = BoxGeometry;
var SphereGeometry = (
/** @class */
function(_super) {
__extends(SphereGeometry2, _super);
function SphereGeometry2(id, scene, segments, diameter, canBeRegenerated, mesh2, side) {
if (mesh2 === void 0) {
mesh2 = null;
}
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.segments = segments;
_this.diameter = diameter;
_this.side = side;
return _this;
}
SphereGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
};
SphereGeometry2.prototype.copy = function(id) {
return new SphereGeometry2(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
};
SphereGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.segments = this.segments;
serializationObject.diameter = this.diameter;
return serializationObject;
};
SphereGeometry2.Parse = function(parsedSphere, scene) {
if (scene.getGeometryByID(parsedSphere.id)) {
return null;
}
var sphere = new SphereGeometry2(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(sphere, parsedSphere.tags);
}
scene.pushGeometry(sphere, true);
return sphere;
};
return SphereGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.SphereGeometry = SphereGeometry;
var DiscGeometry = (
/** @class */
function(_super) {
__extends(DiscGeometry2, _super);
function DiscGeometry2(id, scene, radius, tessellation, canBeRegenerated, mesh2, side) {
if (mesh2 === void 0) {
mesh2 = null;
}
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.radius = radius;
_this.tessellation = tessellation;
_this.side = side;
return _this;
}
DiscGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
};
DiscGeometry2.prototype.copy = function(id) {
return new DiscGeometry2(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
};
return DiscGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.DiscGeometry = DiscGeometry;
var CylinderGeometry = (
/** @class */
function(_super) {
__extends(CylinderGeometry2, _super);
function CylinderGeometry2(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh2, side) {
if (subdivisions === void 0) {
subdivisions = 1;
}
if (mesh2 === void 0) {
mesh2 = null;
}
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.height = height;
_this.diameterTop = diameterTop;
_this.diameterBottom = diameterBottom;
_this.tessellation = tessellation;
_this.subdivisions = subdivisions;
_this.side = side;
return _this;
}
CylinderGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
};
CylinderGeometry2.prototype.copy = function(id) {
return new CylinderGeometry2(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
};
CylinderGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.height = this.height;
serializationObject.diameterTop = this.diameterTop;
serializationObject.diameterBottom = this.diameterBottom;
serializationObject.tessellation = this.tessellation;
return serializationObject;
};
CylinderGeometry2.Parse = function(parsedCylinder, scene) {
if (scene.getGeometryByID(parsedCylinder.id)) {
return null;
}
var cylinder = new CylinderGeometry2(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
}
scene.pushGeometry(cylinder, true);
return cylinder;
};
return CylinderGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.CylinderGeometry = CylinderGeometry;
var TorusGeometry = (
/** @class */
function(_super) {
__extends(TorusGeometry2, _super);
function TorusGeometry2(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh2, side) {
if (mesh2 === void 0) {
mesh2 = null;
}
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.diameter = diameter;
_this.thickness = thickness;
_this.tessellation = tessellation;
_this.side = side;
return _this;
}
TorusGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
};
TorusGeometry2.prototype.copy = function(id) {
return new TorusGeometry2(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
};
TorusGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.diameter = this.diameter;
serializationObject.thickness = this.thickness;
serializationObject.tessellation = this.tessellation;
return serializationObject;
};
TorusGeometry2.Parse = function(parsedTorus, scene) {
if (scene.getGeometryByID(parsedTorus.id)) {
return null;
}
var torus = new TorusGeometry2(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(torus, parsedTorus.tags);
}
scene.pushGeometry(torus, true);
return torus;
};
return TorusGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.TorusGeometry = TorusGeometry;
var GroundGeometry = (
/** @class */
function(_super) {
__extends(GroundGeometry2, _super);
function GroundGeometry2(id, scene, width, height, subdivisions, canBeRegenerated, mesh2) {
if (mesh2 === void 0) {
mesh2 = null;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.width = width;
_this.height = height;
_this.subdivisions = subdivisions;
return _this;
}
GroundGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
};
GroundGeometry2.prototype.copy = function(id) {
return new GroundGeometry2(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
};
GroundGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.width = this.width;
serializationObject.height = this.height;
serializationObject.subdivisions = this.subdivisions;
return serializationObject;
};
GroundGeometry2.Parse = function(parsedGround, scene) {
if (scene.getGeometryByID(parsedGround.id)) {
return null;
}
var ground = new GroundGeometry2(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(ground, parsedGround.tags);
}
scene.pushGeometry(ground, true);
return ground;
};
return GroundGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.GroundGeometry = GroundGeometry;
var TiledGroundGeometry = (
/** @class */
function(_super) {
__extends(TiledGroundGeometry2, _super);
function TiledGroundGeometry2(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh2) {
if (mesh2 === void 0) {
mesh2 = null;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.xmin = xmin;
_this.zmin = zmin;
_this.xmax = xmax;
_this.zmax = zmax;
_this.subdivisions = subdivisions;
_this.precision = precision;
return _this;
}
TiledGroundGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
};
TiledGroundGeometry2.prototype.copy = function(id) {
return new TiledGroundGeometry2(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
};
return TiledGroundGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.TiledGroundGeometry = TiledGroundGeometry;
var PlaneGeometry = (
/** @class */
function(_super) {
__extends(PlaneGeometry2, _super);
function PlaneGeometry2(id, scene, size, canBeRegenerated, mesh2, side) {
if (mesh2 === void 0) {
mesh2 = null;
}
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.size = size;
_this.side = side;
return _this;
}
PlaneGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
};
PlaneGeometry2.prototype.copy = function(id) {
return new PlaneGeometry2(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
};
PlaneGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.size = this.size;
return serializationObject;
};
PlaneGeometry2.Parse = function(parsedPlane, scene) {
if (scene.getGeometryByID(parsedPlane.id)) {
return null;
}
var plane = new PlaneGeometry2(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(plane, parsedPlane.tags);
}
scene.pushGeometry(plane, true);
return plane;
};
return PlaneGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.PlaneGeometry = PlaneGeometry;
var TorusKnotGeometry = (
/** @class */
function(_super) {
__extends(TorusKnotGeometry2, _super);
function TorusKnotGeometry2(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh2, side) {
if (mesh2 === void 0) {
mesh2 = null;
}
if (side === void 0) {
side = BABYLON2.Mesh.DEFAULTSIDE;
}
var _this = _super.call(this, id, scene, canBeRegenerated, mesh2) || this;
_this.radius = radius;
_this.tube = tube;
_this.radialSegments = radialSegments;
_this.tubularSegments = tubularSegments;
_this.p = p;
_this.q = q;
_this.side = side;
return _this;
}
TorusKnotGeometry2.prototype._regenerateVertexData = function() {
return BABYLON2.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
};
TorusKnotGeometry2.prototype.copy = function(id) {
return new TorusKnotGeometry2(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
};
TorusKnotGeometry2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.radius = this.radius;
serializationObject.tube = this.tube;
serializationObject.radialSegments = this.radialSegments;
serializationObject.tubularSegments = this.tubularSegments;
serializationObject.p = this.p;
serializationObject.q = this.q;
return serializationObject;
};
TorusKnotGeometry2.Parse = function(parsedTorusKnot, scene) {
if (scene.getGeometryByID(parsedTorusKnot.id)) {
return null;
}
var torusKnot = new TorusKnotGeometry2(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
if (BABYLON2.Tags) {
BABYLON2.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
}
scene.pushGeometry(torusKnot, true);
return torusKnot;
};
return TorusKnotGeometry2;
}(_PrimitiveGeometry)
);
BABYLON2.TorusKnotGeometry = TorusKnotGeometry;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PerformanceMonitor = (
/** @class */
function() {
function PerformanceMonitor2(frameSampleSize) {
if (frameSampleSize === void 0) {
frameSampleSize = 30;
}
this._enabled = true;
this._rollingFrameTime = new RollingAverage(frameSampleSize);
}
PerformanceMonitor2.prototype.sampleFrame = function(timeMs) {
if (timeMs === void 0) {
timeMs = BABYLON2.Tools.Now;
}
if (!this._enabled) {
return;
}
if (this._lastFrameTimeMs != null) {
var dt = timeMs - this._lastFrameTimeMs;
this._rollingFrameTime.add(dt);
}
this._lastFrameTimeMs = timeMs;
};
Object.defineProperty(PerformanceMonitor2.prototype, "averageFrameTime", {
/**
* Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
*/
get: function() {
return this._rollingFrameTime.average;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor2.prototype, "averageFrameTimeVariance", {
/**
* Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
*/
get: function() {
return this._rollingFrameTime.variance;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor2.prototype, "instantaneousFrameTime", {
/**
* Returns the frame time of the most recent frame
*/
get: function() {
return this._rollingFrameTime.history(0);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor2.prototype, "averageFPS", {
/**
* Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
*/
get: function() {
return 1e3 / this._rollingFrameTime.average;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor2.prototype, "instantaneousFPS", {
/**
* Returns the average framerate in frames per second using the most recent frame time
*/
get: function() {
var history = this._rollingFrameTime.history(0);
if (history === 0) {
return 0;
}
return 1e3 / history;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PerformanceMonitor2.prototype, "isSaturated", {
/**
* Returns true if enough samples have been taken to completely fill the sliding window
*/
get: function() {
return this._rollingFrameTime.isSaturated();
},
enumerable: true,
configurable: true
});
PerformanceMonitor2.prototype.enable = function() {
this._enabled = true;
};
PerformanceMonitor2.prototype.disable = function() {
this._enabled = false;
this._lastFrameTimeMs = null;
};
Object.defineProperty(PerformanceMonitor2.prototype, "isEnabled", {
/**
* Returns true if sampling is enabled
*/
get: function() {
return this._enabled;
},
enumerable: true,
configurable: true
});
PerformanceMonitor2.prototype.reset = function() {
this._lastFrameTimeMs = null;
this._rollingFrameTime.reset();
};
return PerformanceMonitor2;
}()
);
BABYLON2.PerformanceMonitor = PerformanceMonitor;
var RollingAverage = (
/** @class */
function() {
function RollingAverage2(length) {
this._samples = new Array(length);
this.reset();
}
RollingAverage2.prototype.add = function(v) {
var delta;
if (this.isSaturated()) {
var bottomValue = this._samples[this._pos];
delta = bottomValue - this.average;
this.average -= delta / (this._sampleCount - 1);
this._m2 -= delta * (bottomValue - this.average);
} else {
this._sampleCount++;
}
delta = v - this.average;
this.average += delta / this._sampleCount;
this._m2 += delta * (v - this.average);
this.variance = this._m2 / (this._sampleCount - 1);
this._samples[this._pos] = v;
this._pos++;
this._pos %= this._samples.length;
};
RollingAverage2.prototype.history = function(i2) {
if (i2 >= this._sampleCount || i2 >= this._samples.length) {
return 0;
}
var i0 = this._wrapPosition(this._pos - 1);
return this._samples[this._wrapPosition(i0 - i2)];
};
RollingAverage2.prototype.isSaturated = function() {
return this._sampleCount >= this._samples.length;
};
RollingAverage2.prototype.reset = function() {
this.average = 0;
this.variance = 0;
this._sampleCount = 0;
this._pos = 0;
this._m2 = 0;
};
RollingAverage2.prototype._wrapPosition = function(i2) {
var max = this._samples.length;
return (i2 % max + max) % max;
};
return RollingAverage2;
}()
);
BABYLON2.RollingAverage = RollingAverage;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MaterialHelper = (
/** @class */
function() {
function MaterialHelper2() {
}
MaterialHelper2.BindEyePosition = function(effect, scene) {
if (scene._forcedViewPosition) {
effect.setVector3("vEyePosition", scene._forcedViewPosition);
return;
}
effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
};
MaterialHelper2.PrepareDefinesForMergedUV = function(texture, defines, key) {
defines._needUVs = true;
defines[key] = true;
if (texture.getTextureMatrix().isIdentity(true)) {
defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
if (texture.coordinatesIndex === 0) {
defines["MAINUV1"] = true;
} else {
defines["MAINUV2"] = true;
}
} else {
defines[key + "DIRECTUV"] = 0;
}
};
MaterialHelper2.BindTextureMatrix = function(texture, uniformBuffer, key) {
var matrix = texture.getTextureMatrix();
if (!matrix.isIdentity(true)) {
uniformBuffer.updateMatrix(key + "Matrix", matrix);
}
};
MaterialHelper2.PrepareDefinesForMisc = function(mesh2, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
if (defines._areMiscDirty) {
defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
defines["POINTSIZE"] = pointsCloud;
defines["FOG"] = scene.fogEnabled && mesh2.applyFog && scene.fogMode !== BABYLON2.Scene.FOGMODE_NONE && fogEnabled;
defines["NONUNIFORMSCALING"] = mesh2.nonUniformScaling;
defines["ALPHATEST"] = alphaTest;
}
};
MaterialHelper2.PrepareDefinesForFrameBoundValues = function(scene, engine, defines, useInstances, useClipPlane) {
if (useClipPlane === void 0) {
useClipPlane = null;
}
var changed = false;
var useClipPlane1 = false;
var useClipPlane2 = false;
var useClipPlane3 = false;
var useClipPlane4 = false;
useClipPlane1 = useClipPlane == null ? scene.clipPlane !== void 0 && scene.clipPlane !== null : useClipPlane;
useClipPlane2 = useClipPlane == null ? scene.clipPlane2 !== void 0 && scene.clipPlane2 !== null : useClipPlane;
useClipPlane3 = useClipPlane == null ? scene.clipPlane3 !== void 0 && scene.clipPlane3 !== null : useClipPlane;
useClipPlane4 = useClipPlane == null ? scene.clipPlane4 !== void 0 && scene.clipPlane4 !== null : useClipPlane;
if (defines["CLIPPLANE"] !== useClipPlane1) {
defines["CLIPPLANE"] = useClipPlane1;
changed = true;
}
if (defines["CLIPPLANE2"] !== useClipPlane2) {
defines["CLIPPLANE2"] = useClipPlane2;
changed = true;
}
if (defines["CLIPPLANE3"] !== useClipPlane3) {
defines["CLIPPLANE3"] = useClipPlane3;
changed = true;
}
if (defines["CLIPPLANE4"] !== useClipPlane4) {
defines["CLIPPLANE4"] = useClipPlane4;
changed = true;
}
if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
changed = true;
}
if (defines["INSTANCES"] !== useInstances) {
defines["INSTANCES"] = useInstances;
changed = true;
}
if (changed) {
defines.markAsUnprocessed();
}
};
MaterialHelper2.PrepareDefinesForAttributes = function(mesh2, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
if (useMorphTargets === void 0) {
useMorphTargets = false;
}
if (useVertexAlpha === void 0) {
useVertexAlpha = true;
}
if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
return false;
}
defines._normals = defines._needNormals;
defines._uvs = defines._needUVs;
defines["NORMAL"] = defines._needNormals && mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind);
if (defines._needNormals && mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.TangentKind)) {
defines["TANGENT"] = true;
}
if (defines._needUVs) {
defines["UV1"] = mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind);
defines["UV2"] = mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind);
} else {
defines["UV1"] = false;
defines["UV2"] = false;
}
if (useVertexColor) {
var hasVertexColors = mesh2.useVertexColors && mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.ColorKind);
defines["VERTEXCOLOR"] = hasVertexColors;
defines["VERTEXALPHA"] = mesh2.hasVertexAlpha && hasVertexColors && useVertexAlpha;
}
if (useBones) {
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
defines["NUM_BONE_INFLUENCERS"] = mesh2.numBoneInfluencers;
defines["BonesPerMesh"] = mesh2.skeleton.bones.length + 1;
} else {
defines["NUM_BONE_INFLUENCERS"] = 0;
defines["BonesPerMesh"] = 0;
}
}
if (useMorphTargets) {
var manager = mesh2.morphTargetManager;
if (manager) {
defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
defines["MORPHTARGETS"] = manager.numInfluencers > 0;
defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
} else {
defines["MORPHTARGETS_TANGENT"] = false;
defines["MORPHTARGETS_NORMAL"] = false;
defines["MORPHTARGETS"] = false;
defines["NUM_MORPH_INFLUENCERS"] = 0;
}
}
return true;
};
MaterialHelper2.PrepareDefinesForLights = function(scene, mesh2, defines, specularSupported, maxSimultaneousLights, disableLighting) {
if (maxSimultaneousLights === void 0) {
maxSimultaneousLights = 4;
}
if (disableLighting === void 0) {
disableLighting = false;
}
if (!defines._areLightsDirty) {
return defines._needNormals;
}
var lightIndex = 0;
var needNormals = false;
var needRebuild = false;
var lightmapMode = false;
var shadowEnabled = false;
var specularEnabled = false;
if (scene.lightsEnabled && !disableLighting) {
for (var _i = 0, _a = mesh2._lightSources; _i < _a.length; _i++) {
var light = _a[_i];
needNormals = true;
if (defines["LIGHT" + lightIndex] === void 0) {
needRebuild = true;
}
defines["LIGHT" + lightIndex] = true;
defines["SPOTLIGHT" + lightIndex] = false;
defines["HEMILIGHT" + lightIndex] = false;
defines["POINTLIGHT" + lightIndex] = false;
defines["DIRLIGHT" + lightIndex] = false;
light.prepareLightSpecificDefines(defines, lightIndex);
defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
switch (light.falloffType) {
case BABYLON2.Light.FALLOFF_GLTF:
defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
break;
case BABYLON2.Light.FALLOFF_PHYSICAL:
defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
break;
case BABYLON2.Light.FALLOFF_STANDARD:
defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
break;
}
if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
specularEnabled = true;
}
defines["SHADOW" + lightIndex] = false;
defines["SHADOWPCF" + lightIndex] = false;
defines["SHADOWPCSS" + lightIndex] = false;
defines["SHADOWPOISSON" + lightIndex] = false;
defines["SHADOWESM" + lightIndex] = false;
defines["SHADOWCUBE" + lightIndex] = false;
defines["SHADOWLOWQUALITY" + lightIndex] = false;
defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
if (mesh2 && mesh2.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
var shadowGenerator = light.getShadowGenerator();
if (shadowGenerator) {
var shadowMap = shadowGenerator.getShadowMap();
if (shadowMap) {
if (shadowMap.renderList && shadowMap.renderList.length > 0) {
shadowEnabled = true;
shadowGenerator.prepareDefines(defines, lightIndex);
}
}
}
}
if (light.lightmapMode != BABYLON2.Light.LIGHTMAP_DEFAULT) {
lightmapMode = true;
defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
defines["LIGHTMAPNOSPECULAR" + lightIndex] = light.lightmapMode == BABYLON2.Light.LIGHTMAP_SHADOWSONLY;
} else {
defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
}
lightIndex++;
if (lightIndex === maxSimultaneousLights) {
break;
}
}
}
defines["SPECULARTERM"] = specularEnabled;
defines["SHADOWS"] = shadowEnabled;
for (var index = lightIndex; index < maxSimultaneousLights; index++) {
if (defines["LIGHT" + index] !== void 0) {
defines["LIGHT" + index] = false;
defines["HEMILIGHT" + lightIndex] = false;
defines["POINTLIGHT" + lightIndex] = false;
defines["DIRLIGHT" + lightIndex] = false;
defines["SPOTLIGHT" + lightIndex] = false;
defines["SHADOW" + lightIndex] = false;
}
}
var caps = scene.getEngine().getCaps();
if (defines["SHADOWFLOAT"] === void 0) {
needRebuild = true;
}
defines["SHADOWFLOAT"] = shadowEnabled && (caps.textureFloatRender && caps.textureFloatLinearFiltering || caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering);
defines["LIGHTMAPEXCLUDED"] = lightmapMode;
if (needRebuild) {
defines.rebuild();
}
return needNormals;
};
MaterialHelper2.PrepareUniformsAndSamplersList = function(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
if (maxSimultaneousLights === void 0) {
maxSimultaneousLights = 4;
}
var uniformsList;
var uniformBuffersList = null;
if (uniformsListOrOptions.uniformsNames) {
var options = uniformsListOrOptions;
uniformsList = options.uniformsNames;
uniformBuffersList = options.uniformBuffersNames;
samplersList = options.samplers;
defines = options.defines;
maxSimultaneousLights = options.maxSimultaneousLights;
} else {
uniformsList = uniformsListOrOptions;
if (!samplersList) {
samplersList = [];
}
}
for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
if (!defines["LIGHT" + lightIndex]) {
break;
}
uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
if (uniformBuffersList) {
uniformBuffersList.push("Light" + lightIndex);
}
samplersList.push("shadowSampler" + lightIndex);
samplersList.push("depthSampler" + lightIndex);
if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
samplersList.push("projectionLightSampler" + lightIndex);
uniformsList.push("textureProjectionMatrix" + lightIndex);
}
}
if (defines["NUM_MORPH_INFLUENCERS"]) {
uniformsList.push("morphTargetInfluences");
}
};
MaterialHelper2.HandleFallbacksForShadows = function(defines, fallbacks, maxSimultaneousLights, rank) {
if (maxSimultaneousLights === void 0) {
maxSimultaneousLights = 4;
}
if (rank === void 0) {
rank = 0;
}
var lightFallbackRank = 0;
for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
if (!defines["LIGHT" + lightIndex]) {
break;
}
if (lightIndex > 0) {
lightFallbackRank = rank + lightIndex;
fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
}
if (!defines["SHADOWS"]) {
if (defines["SHADOW" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOW" + lightIndex);
}
if (defines["SHADOWPCF" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
}
if (defines["SHADOWPCSS" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
}
if (defines["SHADOWPOISSON" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
}
if (defines["SHADOWESM" + lightIndex]) {
fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
}
}
}
return lightFallbackRank++;
};
MaterialHelper2.PrepareAttributesForMorphTargets = function(attribs, mesh2, defines) {
var influencers = defines["NUM_MORPH_INFLUENCERS"];
if (influencers > 0 && BABYLON2.Engine.LastCreatedEngine) {
var maxAttributesCount = BABYLON2.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
var manager = mesh2.morphTargetManager;
var normal = manager && manager.supportsNormals && defines["NORMAL"];
var tangent = manager && manager.supportsTangents && defines["TANGENT"];
for (var index = 0; index < influencers; index++) {
attribs.push(BABYLON2.VertexBuffer.PositionKind + index);
if (normal) {
attribs.push(BABYLON2.VertexBuffer.NormalKind + index);
}
if (tangent) {
attribs.push(BABYLON2.VertexBuffer.TangentKind + index);
}
if (attribs.length > maxAttributesCount) {
BABYLON2.Tools.Error("Cannot add more vertex attributes for mesh " + mesh2.name);
}
}
}
};
MaterialHelper2.PrepareAttributesForBones = function(attribs, mesh2, defines, fallbacks) {
if (defines["NUM_BONE_INFLUENCERS"] > 0) {
fallbacks.addCPUSkinningFallback(0, mesh2);
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (defines["NUM_BONE_INFLUENCERS"] > 4) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
}
}
};
MaterialHelper2.PrepareAttributesForInstances = function(attribs, defines) {
if (defines["INSTANCES"]) {
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
};
MaterialHelper2.BindLightShadow = function(light, scene, mesh2, lightIndex, effect) {
if (light.shadowEnabled && mesh2.receiveShadows) {
var shadowGenerator = light.getShadowGenerator();
if (shadowGenerator) {
shadowGenerator.bindShadowLight(lightIndex, effect);
}
}
};
MaterialHelper2.BindLightProperties = function(light, effect, lightIndex) {
light.transferToEffect(effect, lightIndex + "");
};
MaterialHelper2.BindLights = function(scene, mesh2, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
if (maxSimultaneousLights === void 0) {
maxSimultaneousLights = 4;
}
if (usePhysicalLightFalloff === void 0) {
usePhysicalLightFalloff = false;
}
var len = Math.min(mesh2._lightSources.length, maxSimultaneousLights);
for (var i2 = 0; i2 < len; i2++) {
var light = mesh2._lightSources[i2];
var iAsString = i2.toString();
var scaledIntensity = light.getScaledIntensity();
light._uniformBuffer.bindToEffect(effect, "Light" + i2);
MaterialHelper2.BindLightProperties(light, effect, i2);
light.diffuse.scaleToRef(scaledIntensity, BABYLON2.Tmp.Color3[0]);
light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON2.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
if (defines["SPECULARTERM"]) {
light.specular.scaleToRef(scaledIntensity, BABYLON2.Tmp.Color3[1]);
light._uniformBuffer.updateColor3("vLightSpecular", BABYLON2.Tmp.Color3[1], iAsString);
}
if (scene.shadowsEnabled) {
this.BindLightShadow(light, scene, mesh2, iAsString, effect);
}
light._uniformBuffer.update();
}
};
MaterialHelper2.BindFogParameters = function(scene, mesh2, effect, linearSpace) {
if (linearSpace === void 0) {
linearSpace = false;
}
if (scene.fogEnabled && mesh2.applyFog && scene.fogMode !== BABYLON2.Scene.FOGMODE_NONE) {
effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
if (linearSpace) {
scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
effect.setColor3("vFogColor", this._tempFogColor);
} else {
effect.setColor3("vFogColor", scene.fogColor);
}
}
};
MaterialHelper2.BindBonesParameters = function(mesh2, effect) {
if (!effect || !mesh2) {
return;
}
if (mesh2.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
mesh2.computeBonesUsingShaders = false;
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
var matrices = mesh2.skeleton.getTransformMatrices(mesh2);
if (matrices) {
effect.setMatrices("mBones", matrices);
}
}
};
MaterialHelper2.BindMorphTargetParameters = function(abstractMesh, effect) {
var manager = abstractMesh.morphTargetManager;
if (!abstractMesh || !manager) {
return;
}
effect.setFloatArray("morphTargetInfluences", manager.influences);
};
MaterialHelper2.BindLogDepth = function(defines, effect, scene) {
if (defines["LOGARITHMICDEPTH"]) {
effect.setFloat("logarithmicDepthConstant", 2 / (Math.log(scene.activeCamera.maxZ + 1) / Math.LN2));
}
};
MaterialHelper2.BindClipPlane = function(effect, scene) {
if (scene.clipPlane) {
var clipPlane = scene.clipPlane;
effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
}
if (scene.clipPlane2) {
var clipPlane = scene.clipPlane2;
effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
}
if (scene.clipPlane3) {
var clipPlane = scene.clipPlane3;
effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
}
if (scene.clipPlane4) {
var clipPlane = scene.clipPlane4;
effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
}
};
MaterialHelper2._tempFogColor = BABYLON2.Color3.Black();
return MaterialHelper2;
}()
);
BABYLON2.MaterialHelper = MaterialHelper;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PushMaterial = (
/** @class */
function(_super) {
__extends(PushMaterial2, _super);
function PushMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._normalMatrix = new BABYLON2.Matrix();
_this.storeEffectOnSubMeshes = true;
return _this;
}
PushMaterial2.prototype.getEffect = function() {
return this._activeEffect;
};
PushMaterial2.prototype.isReady = function(mesh2, useInstances) {
if (!mesh2) {
return false;
}
if (!mesh2.subMeshes || mesh2.subMeshes.length === 0) {
return true;
}
return this.isReadyForSubMesh(mesh2, mesh2.subMeshes[0], useInstances);
};
PushMaterial2.prototype.bindOnlyWorldMatrix = function(world) {
this._activeEffect.setMatrix("world", world);
};
PushMaterial2.prototype.bindOnlyNormalMatrix = function(normalMatrix) {
this._activeEffect.setMatrix("normalMatrix", normalMatrix);
};
PushMaterial2.prototype.bind = function(world, mesh2) {
if (!mesh2) {
return;
}
this.bindForSubMesh(world, mesh2, mesh2.subMeshes[0]);
};
PushMaterial2.prototype._afterBind = function(mesh2, effect) {
if (effect === void 0) {
effect = null;
}
_super.prototype._afterBind.call(this, mesh2);
this.getScene()._cachedEffect = effect;
};
PushMaterial2.prototype._mustRebind = function(scene, effect, visibility) {
if (visibility === void 0) {
visibility = 1;
}
return scene.isCachedMaterialInvalid(this, effect, visibility);
};
return PushMaterial2;
}(BABYLON2.Material)
);
BABYLON2.PushMaterial = PushMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var StandardMaterialDefines = (
/** @class */
function(_super) {
__extends(StandardMaterialDefines2, _super);
function StandardMaterialDefines2() {
var _this = _super.call(this) || this;
_this.MAINUV1 = false;
_this.MAINUV2 = false;
_this.DIFFUSE = false;
_this.DIFFUSEDIRECTUV = 0;
_this.AMBIENT = false;
_this.AMBIENTDIRECTUV = 0;
_this.OPACITY = false;
_this.OPACITYDIRECTUV = 0;
_this.OPACITYRGB = false;
_this.REFLECTION = false;
_this.EMISSIVE = false;
_this.EMISSIVEDIRECTUV = 0;
_this.SPECULAR = false;
_this.SPECULARDIRECTUV = 0;
_this.BUMP = false;
_this.BUMPDIRECTUV = 0;
_this.PARALLAX = false;
_this.PARALLAXOCCLUSION = false;
_this.SPECULAROVERALPHA = false;
_this.CLIPPLANE = false;
_this.CLIPPLANE2 = false;
_this.CLIPPLANE3 = false;
_this.CLIPPLANE4 = false;
_this.ALPHATEST = false;
_this.DEPTHPREPASS = false;
_this.ALPHAFROMDIFFUSE = false;
_this.POINTSIZE = false;
_this.FOG = false;
_this.SPECULARTERM = false;
_this.DIFFUSEFRESNEL = false;
_this.OPACITYFRESNEL = false;
_this.REFLECTIONFRESNEL = false;
_this.REFRACTIONFRESNEL = false;
_this.EMISSIVEFRESNEL = false;
_this.FRESNEL = false;
_this.NORMAL = false;
_this.UV1 = false;
_this.UV2 = false;
_this.VERTEXCOLOR = false;
_this.VERTEXALPHA = false;
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.INSTANCES = false;
_this.GLOSSINESS = false;
_this.ROUGHNESS = false;
_this.EMISSIVEASILLUMINATION = false;
_this.LINKEMISSIVEWITHDIFFUSE = false;
_this.REFLECTIONFRESNELFROMSPECULAR = false;
_this.LIGHTMAP = false;
_this.LIGHTMAPDIRECTUV = 0;
_this.OBJECTSPACE_NORMALMAP = false;
_this.USELIGHTMAPASSHADOWMAP = false;
_this.REFLECTIONMAP_3D = false;
_this.REFLECTIONMAP_SPHERICAL = false;
_this.REFLECTIONMAP_PLANAR = false;
_this.REFLECTIONMAP_CUBIC = false;
_this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
_this.REFLECTIONMAP_PROJECTION = false;
_this.REFLECTIONMAP_SKYBOX = false;
_this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
_this.REFLECTIONMAP_EXPLICIT = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
_this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
_this.INVERTCUBICMAP = false;
_this.LOGARITHMICDEPTH = false;
_this.REFRACTION = false;
_this.REFRACTIONMAP_3D = false;
_this.REFLECTIONOVERALPHA = false;
_this.TWOSIDEDLIGHTING = false;
_this.SHADOWFLOAT = false;
_this.MORPHTARGETS = false;
_this.MORPHTARGETS_NORMAL = false;
_this.MORPHTARGETS_TANGENT = false;
_this.NUM_MORPH_INFLUENCERS = 0;
_this.NONUNIFORMSCALING = false;
_this.PREMULTIPLYALPHA = false;
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.TONEMAPPING_ACES = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.IS_REFLECTION_LINEAR = false;
_this.IS_REFRACTION_LINEAR = false;
_this.EXPOSURE = false;
_this.rebuild();
return _this;
}
StandardMaterialDefines2.prototype.setReflectionMode = function(modeToEnable) {
var modes = [
"REFLECTIONMAP_CUBIC",
"REFLECTIONMAP_EXPLICIT",
"REFLECTIONMAP_PLANAR",
"REFLECTIONMAP_PROJECTION",
"REFLECTIONMAP_PROJECTION",
"REFLECTIONMAP_SKYBOX",
"REFLECTIONMAP_SPHERICAL",
"REFLECTIONMAP_EQUIRECTANGULAR",
"REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
"REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
];
for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
var mode = modes_1[_i];
this[mode] = mode === modeToEnable;
}
};
return StandardMaterialDefines2;
}(BABYLON2.MaterialDefines)
);
BABYLON2.StandardMaterialDefines = StandardMaterialDefines;
var StandardMaterial = (
/** @class */
function(_super) {
__extends(StandardMaterial2, _super);
function StandardMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.ambientColor = new BABYLON2.Color3(0, 0, 0);
_this.diffuseColor = new BABYLON2.Color3(1, 1, 1);
_this.specularColor = new BABYLON2.Color3(1, 1, 1);
_this.emissiveColor = new BABYLON2.Color3(0, 0, 0);
_this.specularPower = 64;
_this._useAlphaFromDiffuseTexture = false;
_this._useEmissiveAsIllumination = false;
_this._linkEmissiveWithDiffuse = false;
_this._useSpecularOverAlpha = false;
_this._useReflectionOverAlpha = false;
_this._disableLighting = false;
_this._useObjectSpaceNormalMap = false;
_this._useParallax = false;
_this._useParallaxOcclusion = false;
_this.parallaxScaleBias = 0.05;
_this._roughness = 0;
_this.indexOfRefraction = 0.98;
_this.invertRefractionY = true;
_this.alphaCutOff = 0.4;
_this._useLightmapAsShadowmap = false;
_this._useReflectionFresnelFromSpecular = false;
_this._useGlossinessFromSpecularMapAlpha = false;
_this._maxSimultaneousLights = 4;
_this._invertNormalMapX = false;
_this._invertNormalMapY = false;
_this._twoSidedLighting = false;
_this._renderTargets = new BABYLON2.SmartArray(16);
_this._worldViewProjectionMatrix = BABYLON2.Matrix.Zero();
_this._globalAmbientColor = new BABYLON2.Color3(0, 0, 0);
_this._attachImageProcessingConfiguration(null);
_this.getRenderTargetTextures = function() {
_this._renderTargets.reset();
if (StandardMaterial2.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
_this._renderTargets.push(_this._reflectionTexture);
}
if (StandardMaterial2.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
_this._renderTargets.push(_this._refractionTexture);
}
return _this._renderTargets;
};
return _this;
}
Object.defineProperty(StandardMaterial2.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function() {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function(value) {
this._attachImageProcessingConfiguration(value);
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
StandardMaterial2.prototype._attachImageProcessingConfiguration = function(configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
} else {
this._imageProcessingConfiguration = configuration;
}
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function(conf) {
_this._markAllSubMeshesAsImageProcessingDirty();
});
}
};
Object.defineProperty(StandardMaterial2.prototype, "cameraColorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2.prototype, "cameraColorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2.prototype, "cameraToneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function() {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function(value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2.prototype, "cameraExposure", {
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
get: function() {
return this._imageProcessingConfiguration.exposure;
},
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
set: function(value) {
this._imageProcessingConfiguration.exposure = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2.prototype, "cameraContrast", {
/**
* Gets The camera contrast used on this material.
*/
get: function() {
return this._imageProcessingConfiguration.contrast;
},
/**
* Sets The camera contrast used on this material.
*/
set: function(value) {
this._imageProcessingConfiguration.contrast = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2.prototype, "cameraColorGradingTexture", {
/**
* Gets the Color Grading 2D Lookup Texture.
*/
get: function() {
return this._imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets the Color Grading 2D Lookup Texture.
*/
set: function(value) {
this._imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2.prototype, "cameraColorCurves", {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
get: function() {
return this._imageProcessingConfiguration.colorCurves;
},
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
set: function(value) {
this._imageProcessingConfiguration.colorCurves = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2.prototype, "hasRenderTargetTextures", {
/**
* Gets a boolean indicating that current material needs to register RTT
*/
get: function() {
if (StandardMaterial2.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
return true;
}
if (StandardMaterial2.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
return true;
}
return false;
},
enumerable: true,
configurable: true
});
StandardMaterial2.prototype.getClassName = function() {
return "StandardMaterial";
};
Object.defineProperty(StandardMaterial2.prototype, "useLogarithmicDepth", {
/**
* In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
* You can try switching to logarithmic depth.
* @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
*/
get: function() {
return this._useLogarithmicDepth;
},
set: function(value) {
this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
this._markAllSubMeshesAsMiscDirty();
},
enumerable: true,
configurable: true
});
StandardMaterial2.prototype.needAlphaBlending = function() {
return this.alpha < 1 || this._opacityTexture != null || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
};
StandardMaterial2.prototype.needAlphaTesting = function() {
return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
};
StandardMaterial2.prototype._shouldUseAlphaFromDiffuseTexture = function() {
return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
};
StandardMaterial2.prototype.getAlphaTestTexture = function() {
return this._diffuseTexture;
};
StandardMaterial2.prototype.isReadyForSubMesh = function(mesh2, subMesh, useInstances) {
if (useInstances === void 0) {
useInstances = false;
}
if (subMesh.effect && this.isFrozen) {
if (this._wasPreviouslyReady) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new StandardMaterialDefines();
}
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!this.checkReadyOnEveryCall && subMesh.effect) {
if (defines._renderId === scene.getRenderId()) {
return true;
}
}
var engine = scene.getEngine();
defines._needNormals = BABYLON2.MaterialHelper.PrepareDefinesForLights(scene, mesh2, defines, true, this._maxSimultaneousLights, this._disableLighting);
if (defines._areTexturesDirty) {
defines._needUVs = false;
defines.MAINUV1 = false;
defines.MAINUV2 = false;
if (scene.texturesEnabled) {
if (this._diffuseTexture && StandardMaterial2.DiffuseTextureEnabled) {
if (!this._diffuseTexture.isReadyOrNotBlocking()) {
return false;
} else {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
}
} else {
defines.DIFFUSE = false;
}
if (this._ambientTexture && StandardMaterial2.AmbientTextureEnabled) {
if (!this._ambientTexture.isReadyOrNotBlocking()) {
return false;
} else {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
}
} else {
defines.AMBIENT = false;
}
if (this._opacityTexture && StandardMaterial2.OpacityTextureEnabled) {
if (!this._opacityTexture.isReadyOrNotBlocking()) {
return false;
} else {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
}
} else {
defines.OPACITY = false;
}
if (this._reflectionTexture && StandardMaterial2.ReflectionTextureEnabled) {
if (!this._reflectionTexture.isReadyOrNotBlocking()) {
return false;
} else {
defines._needNormals = true;
defines.REFLECTION = true;
defines.ROUGHNESS = this._roughness > 0;
defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
defines.INVERTCUBICMAP = this._reflectionTexture.coordinatesMode === BABYLON2.Texture.INVCUBIC_MODE;
defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
switch (this._reflectionTexture.coordinatesMode) {
case BABYLON2.Texture.EXPLICIT_MODE:
defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
break;
case BABYLON2.Texture.PLANAR_MODE:
defines.setReflectionMode("REFLECTIONMAP_PLANAR");
break;
case BABYLON2.Texture.PROJECTION_MODE:
defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
break;
case BABYLON2.Texture.SKYBOX_MODE:
defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
break;
case BABYLON2.Texture.SPHERICAL_MODE:
defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
break;
case BABYLON2.Texture.EQUIRECTANGULAR_MODE:
defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
break;
case BABYLON2.Texture.FIXED_EQUIRECTANGULAR_MODE:
defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
break;
case BABYLON2.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
break;
case BABYLON2.Texture.CUBIC_MODE:
case BABYLON2.Texture.INVCUBIC_MODE:
default:
defines.setReflectionMode("REFLECTIONMAP_CUBIC");
break;
}
defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
}
} else {
defines.REFLECTION = false;
}
if (this._emissiveTexture && StandardMaterial2.EmissiveTextureEnabled) {
if (!this._emissiveTexture.isReadyOrNotBlocking()) {
return false;
} else {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
}
} else {
defines.EMISSIVE = false;
}
if (this._lightmapTexture && StandardMaterial2.LightmapTextureEnabled) {
if (!this._lightmapTexture.isReadyOrNotBlocking()) {
return false;
} else {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
}
} else {
defines.LIGHTMAP = false;
}
if (this._specularTexture && StandardMaterial2.SpecularTextureEnabled) {
if (!this._specularTexture.isReadyOrNotBlocking()) {
return false;
} else {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
}
} else {
defines.SPECULAR = false;
}
if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial2.BumpTextureEnabled) {
if (!this._bumpTexture.isReady()) {
return false;
} else {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
defines.PARALLAX = this._useParallax;
defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
}
defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
} else {
defines.BUMP = false;
}
if (this._refractionTexture && StandardMaterial2.RefractionTextureEnabled) {
if (!this._refractionTexture.isReadyOrNotBlocking()) {
return false;
} else {
defines._needUVs = true;
defines.REFRACTION = true;
defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
}
} else {
defines.REFRACTION = false;
}
defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
} else {
defines.DIFFUSE = false;
defines.AMBIENT = false;
defines.OPACITY = false;
defines.REFLECTION = false;
defines.EMISSIVE = false;
defines.LIGHTMAP = false;
defines.BUMP = false;
defines.REFRACTION = false;
}
defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
defines.PREMULTIPLYALPHA = this.alphaMode === BABYLON2.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON2.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
this._imageProcessingConfiguration.prepareDefines(defines);
defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace;
defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace;
}
if (defines._areFresnelDirty) {
if (StandardMaterial2.FresnelEnabled) {
if (this._diffuseFresnelParameters || this._opacityFresnelParameters || this._emissiveFresnelParameters || this._refractionFresnelParameters || this._reflectionFresnelParameters) {
defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled;
defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled;
defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled;
defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled;
defines._needNormals = true;
defines.FRESNEL = true;
}
} else {
defines.FRESNEL = false;
}
}
BABYLON2.MaterialHelper.PrepareDefinesForMisc(mesh2, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh2), defines);
BABYLON2.MaterialHelper.PrepareDefinesForAttributes(mesh2, defines, true, true, true);
BABYLON2.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
if (defines.isDirty) {
defines.markAsProcessed();
scene.resetCachedMaterial();
var fallbacks = new BABYLON2.EffectFallbacks();
if (defines.REFLECTION) {
fallbacks.addFallback(0, "REFLECTION");
}
if (defines.SPECULAR) {
fallbacks.addFallback(0, "SPECULAR");
}
if (defines.BUMP) {
fallbacks.addFallback(0, "BUMP");
}
if (defines.PARALLAX) {
fallbacks.addFallback(1, "PARALLAX");
}
if (defines.PARALLAXOCCLUSION) {
fallbacks.addFallback(0, "PARALLAXOCCLUSION");
}
if (defines.SPECULAROVERALPHA) {
fallbacks.addFallback(0, "SPECULAROVERALPHA");
}
if (defines.FOG) {
fallbacks.addFallback(1, "FOG");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(0, "POINTSIZE");
}
if (defines.LOGARITHMICDEPTH) {
fallbacks.addFallback(0, "LOGARITHMICDEPTH");
}
BABYLON2.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
if (defines.SPECULARTERM) {
fallbacks.addFallback(0, "SPECULARTERM");
}
if (defines.DIFFUSEFRESNEL) {
fallbacks.addFallback(1, "DIFFUSEFRESNEL");
}
if (defines.OPACITYFRESNEL) {
fallbacks.addFallback(2, "OPACITYFRESNEL");
}
if (defines.REFLECTIONFRESNEL) {
fallbacks.addFallback(3, "REFLECTIONFRESNEL");
}
if (defines.EMISSIVEFRESNEL) {
fallbacks.addFallback(4, "EMISSIVEFRESNEL");
}
if (defines.FRESNEL) {
fallbacks.addFallback(4, "FRESNEL");
}
var attribs = [BABYLON2.VertexBuffer.PositionKind];
if (defines.NORMAL) {
attribs.push(BABYLON2.VertexBuffer.NormalKind);
}
if (defines.UV1) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
}
if (defines.UV2) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
}
if (defines.VERTEXCOLOR) {
attribs.push(BABYLON2.VertexBuffer.ColorKind);
}
BABYLON2.MaterialHelper.PrepareAttributesForBones(attribs, mesh2, defines, fallbacks);
BABYLON2.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
BABYLON2.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh2, defines);
var shaderName = "default";
var uniforms = [
"world",
"view",
"viewProjection",
"vEyePosition",
"vLightsType",
"vAmbientColor",
"vDiffuseColor",
"vSpecularColor",
"vEmissiveColor",
"vFogInfos",
"vFogColor",
"pointSize",
"vDiffuseInfos",
"vAmbientInfos",
"vOpacityInfos",
"vReflectionInfos",
"vEmissiveInfos",
"vSpecularInfos",
"vBumpInfos",
"vLightmapInfos",
"vRefractionInfos",
"mBones",
"vClipPlane",
"vClipPlane2",
"vClipPlane3",
"vClipPlane4",
"diffuseMatrix",
"ambientMatrix",
"opacityMatrix",
"reflectionMatrix",
"emissiveMatrix",
"specularMatrix",
"bumpMatrix",
"normalMatrix",
"lightmapMatrix",
"refractionMatrix",
"diffuseLeftColor",
"diffuseRightColor",
"opacityParts",
"reflectionLeftColor",
"reflectionRightColor",
"emissiveLeftColor",
"emissiveRightColor",
"refractionLeftColor",
"refractionRightColor",
"vReflectionPosition",
"vReflectionSize",
"logarithmicDepthConstant",
"vTangentSpaceParams",
"alphaCutOff"
];
var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
var uniformBuffers = ["Material", "Scene"];
if (BABYLON2.ImageProcessingConfiguration) {
BABYLON2.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
BABYLON2.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
}
BABYLON2.MaterialHelper.PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers,
defines,
maxSimultaneousLights: this._maxSimultaneousLights
});
if (this.customShaderNameResolve) {
shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
}
var join = defines.toString();
subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers,
defines: join,
fallbacks,
onCompiled: this.onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
}, engine), defines);
this.buildUniformLayout();
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
this._wasPreviouslyReady = true;
return true;
};
StandardMaterial2.prototype.buildUniformLayout = function() {
this._uniformBuffer.addUniform("diffuseLeftColor", 4);
this._uniformBuffer.addUniform("diffuseRightColor", 4);
this._uniformBuffer.addUniform("opacityParts", 4);
this._uniformBuffer.addUniform("reflectionLeftColor", 4);
this._uniformBuffer.addUniform("reflectionRightColor", 4);
this._uniformBuffer.addUniform("refractionLeftColor", 4);
this._uniformBuffer.addUniform("refractionRightColor", 4);
this._uniformBuffer.addUniform("emissiveLeftColor", 4);
this._uniformBuffer.addUniform("emissiveRightColor", 4);
this._uniformBuffer.addUniform("vDiffuseInfos", 2);
this._uniformBuffer.addUniform("vAmbientInfos", 2);
this._uniformBuffer.addUniform("vOpacityInfos", 2);
this._uniformBuffer.addUniform("vReflectionInfos", 2);
this._uniformBuffer.addUniform("vReflectionPosition", 3);
this._uniformBuffer.addUniform("vReflectionSize", 3);
this._uniformBuffer.addUniform("vEmissiveInfos", 2);
this._uniformBuffer.addUniform("vLightmapInfos", 2);
this._uniformBuffer.addUniform("vSpecularInfos", 2);
this._uniformBuffer.addUniform("vBumpInfos", 3);
this._uniformBuffer.addUniform("diffuseMatrix", 16);
this._uniformBuffer.addUniform("ambientMatrix", 16);
this._uniformBuffer.addUniform("opacityMatrix", 16);
this._uniformBuffer.addUniform("reflectionMatrix", 16);
this._uniformBuffer.addUniform("emissiveMatrix", 16);
this._uniformBuffer.addUniform("lightmapMatrix", 16);
this._uniformBuffer.addUniform("specularMatrix", 16);
this._uniformBuffer.addUniform("bumpMatrix", 16);
this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
this._uniformBuffer.addUniform("refractionMatrix", 16);
this._uniformBuffer.addUniform("vRefractionInfos", 4);
this._uniformBuffer.addUniform("vSpecularColor", 4);
this._uniformBuffer.addUniform("vEmissiveColor", 3);
this._uniformBuffer.addUniform("vDiffuseColor", 4);
this._uniformBuffer.addUniform("pointSize", 1);
this._uniformBuffer.create();
};
StandardMaterial2.prototype.unbind = function() {
if (this._activeEffect) {
var needFlag = false;
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._activeEffect.setTexture("reflection2DSampler", null);
needFlag = true;
}
if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
this._activeEffect.setTexture("refraction2DSampler", null);
needFlag = true;
}
if (needFlag) {
this._markAllSubMeshesAsTexturesDirty();
}
}
_super.prototype.unbind.call(this);
};
StandardMaterial2.prototype.bindForSubMesh = function(world, mesh2, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
this.bindOnlyWorldMatrix(world);
if (defines.OBJECTSPACE_NORMALMAP) {
world.toNormalMatrix(this._normalMatrix);
this.bindOnlyNormalMatrix(this._normalMatrix);
}
var mustRebind = this._mustRebind(scene, effect, mesh2.visibility);
BABYLON2.MaterialHelper.BindBonesParameters(mesh2, effect);
if (mustRebind) {
this._uniformBuffer.bindToEffect(effect, "Material");
this.bindViewProjection(effect);
if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
if (StandardMaterial2.FresnelEnabled && defines.FRESNEL) {
if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
}
if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("opacityParts", new BABYLON2.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
}
if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
}
if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
}
if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
}
}
if (scene.texturesEnabled) {
if (this._diffuseTexture && StandardMaterial2.DiffuseTextureEnabled) {
this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
if (this._diffuseTexture.hasAlpha) {
effect.setFloat("alphaCutOff", this.alphaCutOff);
}
}
if (this._ambientTexture && StandardMaterial2.AmbientTextureEnabled) {
this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
}
if (this._opacityTexture && StandardMaterial2.OpacityTextureEnabled) {
this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
}
if (this._reflectionTexture && StandardMaterial2.ReflectionTextureEnabled) {
this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
if (this._reflectionTexture.boundingBoxSize) {
var cubeTexture = this._reflectionTexture;
this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
}
}
if (this._emissiveTexture && StandardMaterial2.EmissiveTextureEnabled) {
this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
}
if (this._lightmapTexture && StandardMaterial2.LightmapTextureEnabled) {
this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
}
if (this._specularTexture && StandardMaterial2.SpecularTextureEnabled) {
this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial2.BumpTextureEnabled) {
this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1 / this._bumpTexture.level, this.parallaxScaleBias);
BABYLON2.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
if (scene._mirroredCameraPosition) {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1);
} else {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1);
}
}
if (this._refractionTexture && StandardMaterial2.RefractionTextureEnabled) {
var depth = 1;
if (!this._refractionTexture.isCube) {
this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
if (this._refractionTexture.depth) {
depth = this._refractionTexture.depth;
}
}
this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
}
}
if (this.pointsCloud) {
this._uniformBuffer.updateFloat("pointSize", this.pointSize);
}
if (defines.SPECULARTERM) {
this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
}
this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh2.visibility);
}
if (scene.texturesEnabled) {
if (this._diffuseTexture && StandardMaterial2.DiffuseTextureEnabled) {
effect.setTexture("diffuseSampler", this._diffuseTexture);
}
if (this._ambientTexture && StandardMaterial2.AmbientTextureEnabled) {
effect.setTexture("ambientSampler", this._ambientTexture);
}
if (this._opacityTexture && StandardMaterial2.OpacityTextureEnabled) {
effect.setTexture("opacitySampler", this._opacityTexture);
}
if (this._reflectionTexture && StandardMaterial2.ReflectionTextureEnabled) {
if (this._reflectionTexture.isCube) {
effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
} else {
effect.setTexture("reflection2DSampler", this._reflectionTexture);
}
}
if (this._emissiveTexture && StandardMaterial2.EmissiveTextureEnabled) {
effect.setTexture("emissiveSampler", this._emissiveTexture);
}
if (this._lightmapTexture && StandardMaterial2.LightmapTextureEnabled) {
effect.setTexture("lightmapSampler", this._lightmapTexture);
}
if (this._specularTexture && StandardMaterial2.SpecularTextureEnabled) {
effect.setTexture("specularSampler", this._specularTexture);
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial2.BumpTextureEnabled) {
effect.setTexture("bumpSampler", this._bumpTexture);
}
if (this._refractionTexture && StandardMaterial2.RefractionTextureEnabled) {
var depth = 1;
if (this._refractionTexture.isCube) {
effect.setTexture("refractionCubeSampler", this._refractionTexture);
} else {
effect.setTexture("refraction2DSampler", this._refractionTexture);
}
}
}
BABYLON2.MaterialHelper.BindClipPlane(effect, scene);
scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
BABYLON2.MaterialHelper.BindEyePosition(effect, scene);
effect.setColor3("vAmbientColor", this._globalAmbientColor);
}
if (mustRebind || !this.isFrozen) {
if (scene.lightsEnabled && !this._disableLighting) {
BABYLON2.MaterialHelper.BindLights(scene, mesh2, effect, defines, this._maxSimultaneousLights);
}
if (scene.fogEnabled && mesh2.applyFog && scene.fogMode !== BABYLON2.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
this.bindView(effect);
}
BABYLON2.MaterialHelper.BindFogParameters(scene, mesh2, effect);
if (defines.NUM_MORPH_INFLUENCERS) {
BABYLON2.MaterialHelper.BindMorphTargetParameters(mesh2, effect);
}
BABYLON2.MaterialHelper.BindLogDepth(defines, effect, scene);
if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
this._imageProcessingConfiguration.bind(this._activeEffect);
}
}
this._uniformBuffer.update();
this._afterBind(mesh2, this._activeEffect);
};
StandardMaterial2.prototype.getAnimatables = function() {
var results = [];
if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
results.push(this._diffuseTexture);
}
if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
results.push(this._ambientTexture);
}
if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
results.push(this._opacityTexture);
}
if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
results.push(this._reflectionTexture);
}
if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
results.push(this._emissiveTexture);
}
if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
results.push(this._specularTexture);
}
if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
results.push(this._bumpTexture);
}
if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
results.push(this._lightmapTexture);
}
if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
results.push(this._refractionTexture);
}
return results;
};
StandardMaterial2.prototype.getActiveTextures = function() {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this._diffuseTexture) {
activeTextures.push(this._diffuseTexture);
}
if (this._ambientTexture) {
activeTextures.push(this._ambientTexture);
}
if (this._opacityTexture) {
activeTextures.push(this._opacityTexture);
}
if (this._reflectionTexture) {
activeTextures.push(this._reflectionTexture);
}
if (this._emissiveTexture) {
activeTextures.push(this._emissiveTexture);
}
if (this._specularTexture) {
activeTextures.push(this._specularTexture);
}
if (this._bumpTexture) {
activeTextures.push(this._bumpTexture);
}
if (this._lightmapTexture) {
activeTextures.push(this._lightmapTexture);
}
if (this._refractionTexture) {
activeTextures.push(this._refractionTexture);
}
return activeTextures;
};
StandardMaterial2.prototype.hasTexture = function(texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this._diffuseTexture === texture) {
return true;
}
if (this._ambientTexture === texture) {
return true;
}
if (this._opacityTexture === texture) {
return true;
}
if (this._reflectionTexture === texture) {
return true;
}
if (this._emissiveTexture === texture) {
return true;
}
if (this._specularTexture === texture) {
return true;
}
if (this._bumpTexture === texture) {
return true;
}
if (this._lightmapTexture === texture) {
return true;
}
if (this._refractionTexture === texture) {
return true;
}
return false;
};
StandardMaterial2.prototype.dispose = function(forceDisposeEffect, forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._diffuseTexture) {
this._diffuseTexture.dispose();
}
if (this._ambientTexture) {
this._ambientTexture.dispose();
}
if (this._opacityTexture) {
this._opacityTexture.dispose();
}
if (this._reflectionTexture) {
this._reflectionTexture.dispose();
}
if (this._emissiveTexture) {
this._emissiveTexture.dispose();
}
if (this._specularTexture) {
this._specularTexture.dispose();
}
if (this._bumpTexture) {
this._bumpTexture.dispose();
}
if (this._lightmapTexture) {
this._lightmapTexture.dispose();
}
if (this._refractionTexture) {
this._refractionTexture.dispose();
}
}
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
};
StandardMaterial2.prototype.clone = function(name, scene) {
var _this = this;
var result = BABYLON2.SerializationHelper.Clone(function() {
return new StandardMaterial2(name, scene || _this.getScene());
}, this);
result.name = name;
result.id = name;
return result;
};
StandardMaterial2.prototype.serialize = function() {
return BABYLON2.SerializationHelper.Serialize(this);
};
StandardMaterial2.Parse = function(source, scene, rootUrl) {
return BABYLON2.SerializationHelper.Parse(function() {
return new StandardMaterial2(source.name, scene);
}, source, scene, rootUrl);
};
Object.defineProperty(StandardMaterial2, "DiffuseTextureEnabled", {
/**
* Are diffuse textures enabled in the application.
*/
get: function() {
return StandardMaterial2._DiffuseTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._DiffuseTextureEnabled === value) {
return;
}
StandardMaterial2._DiffuseTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "AmbientTextureEnabled", {
/**
* Are ambient textures enabled in the application.
*/
get: function() {
return StandardMaterial2._AmbientTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._AmbientTextureEnabled === value) {
return;
}
StandardMaterial2._AmbientTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "OpacityTextureEnabled", {
/**
* Are opacity textures enabled in the application.
*/
get: function() {
return StandardMaterial2._OpacityTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._OpacityTextureEnabled === value) {
return;
}
StandardMaterial2._OpacityTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "ReflectionTextureEnabled", {
/**
* Are reflection textures enabled in the application.
*/
get: function() {
return StandardMaterial2._ReflectionTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._ReflectionTextureEnabled === value) {
return;
}
StandardMaterial2._ReflectionTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "EmissiveTextureEnabled", {
/**
* Are emissive textures enabled in the application.
*/
get: function() {
return StandardMaterial2._EmissiveTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._EmissiveTextureEnabled === value) {
return;
}
StandardMaterial2._EmissiveTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "SpecularTextureEnabled", {
/**
* Are specular textures enabled in the application.
*/
get: function() {
return StandardMaterial2._SpecularTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._SpecularTextureEnabled === value) {
return;
}
StandardMaterial2._SpecularTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "BumpTextureEnabled", {
/**
* Are bump textures enabled in the application.
*/
get: function() {
return StandardMaterial2._BumpTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._BumpTextureEnabled === value) {
return;
}
StandardMaterial2._BumpTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "LightmapTextureEnabled", {
/**
* Are lightmap textures enabled in the application.
*/
get: function() {
return StandardMaterial2._LightmapTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._LightmapTextureEnabled === value) {
return;
}
StandardMaterial2._LightmapTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "RefractionTextureEnabled", {
/**
* Are refraction textures enabled in the application.
*/
get: function() {
return StandardMaterial2._RefractionTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._RefractionTextureEnabled === value) {
return;
}
StandardMaterial2._RefractionTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "ColorGradingTextureEnabled", {
/**
* Are color grading textures enabled in the application.
*/
get: function() {
return StandardMaterial2._ColorGradingTextureEnabled;
},
set: function(value) {
if (StandardMaterial2._ColorGradingTextureEnabled === value) {
return;
}
StandardMaterial2._ColorGradingTextureEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardMaterial2, "FresnelEnabled", {
/**
* Are fresnels enabled in the application.
*/
get: function() {
return StandardMaterial2._FresnelEnabled;
},
set: function(value) {
if (StandardMaterial2._FresnelEnabled === value) {
return;
}
StandardMaterial2._FresnelEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.FresnelDirtyFlag);
},
enumerable: true,
configurable: true
});
StandardMaterial2._DiffuseTextureEnabled = true;
StandardMaterial2._AmbientTextureEnabled = true;
StandardMaterial2._OpacityTextureEnabled = true;
StandardMaterial2._ReflectionTextureEnabled = true;
StandardMaterial2._EmissiveTextureEnabled = true;
StandardMaterial2._SpecularTextureEnabled = true;
StandardMaterial2._BumpTextureEnabled = true;
StandardMaterial2._LightmapTextureEnabled = true;
StandardMaterial2._RefractionTextureEnabled = true;
StandardMaterial2._ColorGradingTextureEnabled = true;
StandardMaterial2._FresnelEnabled = true;
__decorate([
BABYLON2.serializeAsTexture("diffuseTexture")
], StandardMaterial2.prototype, "_diffuseTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], StandardMaterial2.prototype, "diffuseTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("ambientTexture")
], StandardMaterial2.prototype, "_ambientTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "ambientTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("opacityTexture")
], StandardMaterial2.prototype, "_opacityTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], StandardMaterial2.prototype, "opacityTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("reflectionTexture")
], StandardMaterial2.prototype, "_reflectionTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "reflectionTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("emissiveTexture")
], StandardMaterial2.prototype, "_emissiveTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "emissiveTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("specularTexture")
], StandardMaterial2.prototype, "_specularTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "specularTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("bumpTexture")
], StandardMaterial2.prototype, "_bumpTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "bumpTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("lightmapTexture")
], StandardMaterial2.prototype, "_lightmapTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "lightmapTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("refractionTexture")
], StandardMaterial2.prototype, "_refractionTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "refractionTexture", void 0);
__decorate([
BABYLON2.serializeAsColor3("ambient")
], StandardMaterial2.prototype, "ambientColor", void 0);
__decorate([
BABYLON2.serializeAsColor3("diffuse")
], StandardMaterial2.prototype, "diffuseColor", void 0);
__decorate([
BABYLON2.serializeAsColor3("specular")
], StandardMaterial2.prototype, "specularColor", void 0);
__decorate([
BABYLON2.serializeAsColor3("emissive")
], StandardMaterial2.prototype, "emissiveColor", void 0);
__decorate([
BABYLON2.serialize()
], StandardMaterial2.prototype, "specularPower", void 0);
__decorate([
BABYLON2.serialize("useAlphaFromDiffuseTexture")
], StandardMaterial2.prototype, "_useAlphaFromDiffuseTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useAlphaFromDiffuseTexture", void 0);
__decorate([
BABYLON2.serialize("useEmissiveAsIllumination")
], StandardMaterial2.prototype, "_useEmissiveAsIllumination", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useEmissiveAsIllumination", void 0);
__decorate([
BABYLON2.serialize("linkEmissiveWithDiffuse")
], StandardMaterial2.prototype, "_linkEmissiveWithDiffuse", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "linkEmissiveWithDiffuse", void 0);
__decorate([
BABYLON2.serialize("useSpecularOverAlpha")
], StandardMaterial2.prototype, "_useSpecularOverAlpha", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useSpecularOverAlpha", void 0);
__decorate([
BABYLON2.serialize("useReflectionOverAlpha")
], StandardMaterial2.prototype, "_useReflectionOverAlpha", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useReflectionOverAlpha", void 0);
__decorate([
BABYLON2.serialize("disableLighting")
], StandardMaterial2.prototype, "_disableLighting", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], StandardMaterial2.prototype, "disableLighting", void 0);
__decorate([
BABYLON2.serialize("useObjectSpaceNormalMap")
], StandardMaterial2.prototype, "_useObjectSpaceNormalMap", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useObjectSpaceNormalMap", void 0);
__decorate([
BABYLON2.serialize("useParallax")
], StandardMaterial2.prototype, "_useParallax", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useParallax", void 0);
__decorate([
BABYLON2.serialize("useParallaxOcclusion")
], StandardMaterial2.prototype, "_useParallaxOcclusion", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useParallaxOcclusion", void 0);
__decorate([
BABYLON2.serialize()
], StandardMaterial2.prototype, "parallaxScaleBias", void 0);
__decorate([
BABYLON2.serialize("roughness")
], StandardMaterial2.prototype, "_roughness", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "roughness", void 0);
__decorate([
BABYLON2.serialize()
], StandardMaterial2.prototype, "indexOfRefraction", void 0);
__decorate([
BABYLON2.serialize()
], StandardMaterial2.prototype, "invertRefractionY", void 0);
__decorate([
BABYLON2.serialize()
], StandardMaterial2.prototype, "alphaCutOff", void 0);
__decorate([
BABYLON2.serialize("useLightmapAsShadowmap")
], StandardMaterial2.prototype, "_useLightmapAsShadowmap", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useLightmapAsShadowmap", void 0);
__decorate([
BABYLON2.serializeAsFresnelParameters("diffuseFresnelParameters")
], StandardMaterial2.prototype, "_diffuseFresnelParameters", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial2.prototype, "diffuseFresnelParameters", void 0);
__decorate([
BABYLON2.serializeAsFresnelParameters("opacityFresnelParameters")
], StandardMaterial2.prototype, "_opacityFresnelParameters", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
], StandardMaterial2.prototype, "opacityFresnelParameters", void 0);
__decorate([
BABYLON2.serializeAsFresnelParameters("reflectionFresnelParameters")
], StandardMaterial2.prototype, "_reflectionFresnelParameters", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial2.prototype, "reflectionFresnelParameters", void 0);
__decorate([
BABYLON2.serializeAsFresnelParameters("refractionFresnelParameters")
], StandardMaterial2.prototype, "_refractionFresnelParameters", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial2.prototype, "refractionFresnelParameters", void 0);
__decorate([
BABYLON2.serializeAsFresnelParameters("emissiveFresnelParameters")
], StandardMaterial2.prototype, "_emissiveFresnelParameters", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial2.prototype, "emissiveFresnelParameters", void 0);
__decorate([
BABYLON2.serialize("useReflectionFresnelFromSpecular")
], StandardMaterial2.prototype, "_useReflectionFresnelFromSpecular", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsFresnelDirty")
], StandardMaterial2.prototype, "useReflectionFresnelFromSpecular", void 0);
__decorate([
BABYLON2.serialize("useGlossinessFromSpecularMapAlpha")
], StandardMaterial2.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
__decorate([
BABYLON2.serialize("maxSimultaneousLights")
], StandardMaterial2.prototype, "_maxSimultaneousLights", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], StandardMaterial2.prototype, "maxSimultaneousLights", void 0);
__decorate([
BABYLON2.serialize("invertNormalMapX")
], StandardMaterial2.prototype, "_invertNormalMapX", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "invertNormalMapX", void 0);
__decorate([
BABYLON2.serialize("invertNormalMapY")
], StandardMaterial2.prototype, "_invertNormalMapY", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "invertNormalMapY", void 0);
__decorate([
BABYLON2.serialize("twoSidedLighting")
], StandardMaterial2.prototype, "_twoSidedLighting", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], StandardMaterial2.prototype, "twoSidedLighting", void 0);
__decorate([
BABYLON2.serialize()
], StandardMaterial2.prototype, "useLogarithmicDepth", null);
return StandardMaterial2;
}(BABYLON2.PushMaterial)
);
BABYLON2.StandardMaterial = StandardMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SphericalPolynomial = (
/** @class */
function() {
function SphericalPolynomial2() {
this.x = BABYLON2.Vector3.Zero();
this.y = BABYLON2.Vector3.Zero();
this.z = BABYLON2.Vector3.Zero();
this.xx = BABYLON2.Vector3.Zero();
this.yy = BABYLON2.Vector3.Zero();
this.zz = BABYLON2.Vector3.Zero();
this.xy = BABYLON2.Vector3.Zero();
this.yz = BABYLON2.Vector3.Zero();
this.zx = BABYLON2.Vector3.Zero();
}
SphericalPolynomial2.prototype.addAmbient = function(color) {
var colorVector = new BABYLON2.Vector3(color.r, color.g, color.b);
this.xx = this.xx.add(colorVector);
this.yy = this.yy.add(colorVector);
this.zz = this.zz.add(colorVector);
};
SphericalPolynomial2.prototype.scale = function(scale) {
this.x = this.x.scale(scale);
this.y = this.y.scale(scale);
this.z = this.z.scale(scale);
this.xx = this.xx.scale(scale);
this.yy = this.yy.scale(scale);
this.zz = this.zz.scale(scale);
this.yz = this.yz.scale(scale);
this.zx = this.zx.scale(scale);
this.xy = this.xy.scale(scale);
};
SphericalPolynomial2.FromHarmonics = function(harmonics) {
var result = new SphericalPolynomial2();
result.x = harmonics.l11.scale(1.02333);
result.y = harmonics.l1_1.scale(1.02333);
result.z = harmonics.l10.scale(1.02333);
result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
result.yz = harmonics.l2_1.scale(0.858086);
result.zx = harmonics.l21.scale(0.858086);
result.xy = harmonics.l2_2.scale(0.858086);
result.scale(1 / Math.PI);
return result;
};
SphericalPolynomial2.FromArray = function(data2) {
var sp = new SphericalPolynomial2();
BABYLON2.Vector3.FromArrayToRef(data2[0], 0, sp.x);
BABYLON2.Vector3.FromArrayToRef(data2[1], 0, sp.y);
BABYLON2.Vector3.FromArrayToRef(data2[2], 0, sp.z);
BABYLON2.Vector3.FromArrayToRef(data2[3], 0, sp.xx);
BABYLON2.Vector3.FromArrayToRef(data2[4], 0, sp.yy);
BABYLON2.Vector3.FromArrayToRef(data2[5], 0, sp.zz);
BABYLON2.Vector3.FromArrayToRef(data2[6], 0, sp.yz);
BABYLON2.Vector3.FromArrayToRef(data2[7], 0, sp.zx);
BABYLON2.Vector3.FromArrayToRef(data2[8], 0, sp.xy);
return sp;
};
return SphericalPolynomial2;
}()
);
BABYLON2.SphericalPolynomial = SphericalPolynomial;
var SphericalHarmonics = (
/** @class */
function() {
function SphericalHarmonics2() {
this.l00 = BABYLON2.Vector3.Zero();
this.l1_1 = BABYLON2.Vector3.Zero();
this.l10 = BABYLON2.Vector3.Zero();
this.l11 = BABYLON2.Vector3.Zero();
this.l2_2 = BABYLON2.Vector3.Zero();
this.l2_1 = BABYLON2.Vector3.Zero();
this.l20 = BABYLON2.Vector3.Zero();
this.l21 = BABYLON2.Vector3.Zero();
this.lL22 = BABYLON2.Vector3.Zero();
}
SphericalHarmonics2.prototype.addLight = function(direction, color, deltaSolidAngle) {
var colorVector = new BABYLON2.Vector3(color.r, color.g, color.b);
var c = colorVector.scale(deltaSolidAngle);
this.l00 = this.l00.add(c.scale(0.282095));
this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
this.l20 = this.l20.add(c.scale(0.315392 * (3 * direction.z * direction.z - 1)));
this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
};
SphericalHarmonics2.prototype.scale = function(scale) {
this.l00 = this.l00.scale(scale);
this.l1_1 = this.l1_1.scale(scale);
this.l10 = this.l10.scale(scale);
this.l11 = this.l11.scale(scale);
this.l2_2 = this.l2_2.scale(scale);
this.l2_1 = this.l2_1.scale(scale);
this.l20 = this.l20.scale(scale);
this.l21 = this.l21.scale(scale);
this.lL22 = this.lL22.scale(scale);
};
SphericalHarmonics2.prototype.convertIncidentRadianceToIrradiance = function() {
this.l00 = this.l00.scale(3.141593);
this.l1_1 = this.l1_1.scale(2.094395);
this.l10 = this.l10.scale(2.094395);
this.l11 = this.l11.scale(2.094395);
this.l2_2 = this.l2_2.scale(0.785398);
this.l2_1 = this.l2_1.scale(0.785398);
this.l20 = this.l20.scale(0.785398);
this.l21 = this.l21.scale(0.785398);
this.lL22 = this.lL22.scale(0.785398);
};
SphericalHarmonics2.prototype.convertIrradianceToLambertianRadiance = function() {
this.scale(1 / Math.PI);
};
SphericalHarmonics2.FromPolynomial = function(polynomial) {
var result = new SphericalHarmonics2();
result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
result.l1_1 = polynomial.y.scale(0.977204);
result.l10 = polynomial.z.scale(0.977204);
result.l11 = polynomial.x.scale(0.977204);
result.l2_2 = polynomial.xy.scale(1.16538);
result.l2_1 = polynomial.yz.scale(1.16538);
result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
result.l21 = polynomial.zx.scale(1.16538);
result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
result.scale(Math.PI);
return result;
};
SphericalHarmonics2.FromArray = function(data2) {
var sh = new SphericalHarmonics2();
BABYLON2.Vector3.FromArrayToRef(data2[0], 0, sh.l00);
BABYLON2.Vector3.FromArrayToRef(data2[1], 0, sh.l1_1);
BABYLON2.Vector3.FromArrayToRef(data2[2], 0, sh.l10);
BABYLON2.Vector3.FromArrayToRef(data2[3], 0, sh.l11);
BABYLON2.Vector3.FromArrayToRef(data2[4], 0, sh.l2_2);
BABYLON2.Vector3.FromArrayToRef(data2[5], 0, sh.l2_1);
BABYLON2.Vector3.FromArrayToRef(data2[6], 0, sh.l20);
BABYLON2.Vector3.FromArrayToRef(data2[7], 0, sh.l21);
BABYLON2.Vector3.FromArrayToRef(data2[8], 0, sh.lL22);
return sh;
};
return SphericalHarmonics2;
}()
);
BABYLON2.SphericalHarmonics = SphericalHarmonics;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FileFaceOrientation = (
/** @class */
function() {
function FileFaceOrientation2(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
this.name = name;
this.worldAxisForNormal = worldAxisForNormal;
this.worldAxisForFileX = worldAxisForFileX;
this.worldAxisForFileY = worldAxisForFileY;
}
return FileFaceOrientation2;
}()
);
var CubeMapToSphericalPolynomialTools = (
/** @class */
function() {
function CubeMapToSphericalPolynomialTools2() {
}
CubeMapToSphericalPolynomialTools2.ConvertCubeMapTextureToSphericalPolynomial = function(texture) {
if (!texture.isCube) {
return null;
}
var size = texture.getSize().width;
var right = texture.readPixels(0);
var left = texture.readPixels(1);
var up;
var down;
if (texture.isRenderTarget) {
up = texture.readPixels(3);
down = texture.readPixels(2);
} else {
up = texture.readPixels(2);
down = texture.readPixels(3);
}
var front = texture.readPixels(4);
var back = texture.readPixels(5);
var gammaSpace = texture.gammaSpace;
var format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
var type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
if (texture.textureType && texture.textureType !== BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT) {
type = BABYLON2.Engine.TEXTURETYPE_FLOAT;
}
var cubeInfo = {
size,
right,
left,
up,
down,
front,
back,
format,
type,
gammaSpace
};
return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
};
CubeMapToSphericalPolynomialTools2.ConvertCubeMapToSphericalPolynomial = function(cubeInfo) {
var sphericalHarmonics = new BABYLON2.SphericalHarmonics();
var totalSolidAngle = 0;
var du = 2 / cubeInfo.size;
var dv = du;
var minUV = du * 0.5 - 1;
for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
var fileFace = this.FileFaces[faceIndex];
var dataArray = cubeInfo[fileFace.name];
var v = minUV;
var stride = cubeInfo.format === BABYLON2.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
for (var y = 0; y < cubeInfo.size; y++) {
var u = minUV;
for (var x = 0; x < cubeInfo.size; x++) {
var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
worldDirection.normalize();
var deltaSolidAngle = Math.pow(1 + u * u + v * v, -3 / 2);
var r = dataArray[y * cubeInfo.size * stride + x * stride + 0];
var g = dataArray[y * cubeInfo.size * stride + x * stride + 1];
var b2 = dataArray[y * cubeInfo.size * stride + x * stride + 2];
if (cubeInfo.type === BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT) {
r /= 255;
g /= 255;
b2 /= 255;
}
if (cubeInfo.gammaSpace) {
r = Math.pow(BABYLON2.Scalar.Clamp(r), BABYLON2.ToLinearSpace);
g = Math.pow(BABYLON2.Scalar.Clamp(g), BABYLON2.ToLinearSpace);
b2 = Math.pow(BABYLON2.Scalar.Clamp(b2), BABYLON2.ToLinearSpace);
}
var color = new BABYLON2.Color3(r, g, b2);
sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
totalSolidAngle += deltaSolidAngle;
u += du;
}
v += dv;
}
}
var sphereSolidAngle = 4 * Math.PI;
var facesProcessed = 6;
var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6;
var correctionFactor = expectedSolidAngle / totalSolidAngle;
sphericalHarmonics.scale(correctionFactor);
sphericalHarmonics.convertIncidentRadianceToIrradiance();
sphericalHarmonics.convertIrradianceToLambertianRadiance();
return BABYLON2.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
};
CubeMapToSphericalPolynomialTools2.FileFaces = [
new FileFaceOrientation("right", new BABYLON2.Vector3(1, 0, 0), new BABYLON2.Vector3(0, 0, -1), new BABYLON2.Vector3(0, -1, 0)),
new FileFaceOrientation("left", new BABYLON2.Vector3(-1, 0, 0), new BABYLON2.Vector3(0, 0, 1), new BABYLON2.Vector3(0, -1, 0)),
new FileFaceOrientation("up", new BABYLON2.Vector3(0, 1, 0), new BABYLON2.Vector3(1, 0, 0), new BABYLON2.Vector3(0, 0, 1)),
new FileFaceOrientation("down", new BABYLON2.Vector3(0, -1, 0), new BABYLON2.Vector3(1, 0, 0), new BABYLON2.Vector3(0, 0, -1)),
new FileFaceOrientation("front", new BABYLON2.Vector3(0, 0, 1), new BABYLON2.Vector3(1, 0, 0), new BABYLON2.Vector3(0, -1, 0)),
new FileFaceOrientation("back", new BABYLON2.Vector3(0, 0, -1), new BABYLON2.Vector3(-1, 0, 0), new BABYLON2.Vector3(0, -1, 0))
// -Z bottom
];
return CubeMapToSphericalPolynomialTools2;
}()
);
BABYLON2.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PBRMaterialDefines = (
/** @class */
function(_super) {
__extends(PBRMaterialDefines2, _super);
function PBRMaterialDefines2() {
var _this = _super.call(this) || this;
_this.PBR = true;
_this.MAINUV1 = false;
_this.MAINUV2 = false;
_this.UV1 = false;
_this.UV2 = false;
_this.ALBEDO = false;
_this.ALBEDODIRECTUV = 0;
_this.VERTEXCOLOR = false;
_this.AMBIENT = false;
_this.AMBIENTDIRECTUV = 0;
_this.AMBIENTINGRAYSCALE = false;
_this.OPACITY = false;
_this.VERTEXALPHA = false;
_this.OPACITYDIRECTUV = 0;
_this.OPACITYRGB = false;
_this.ALPHATEST = false;
_this.DEPTHPREPASS = false;
_this.ALPHABLEND = false;
_this.ALPHAFROMALBEDO = false;
_this.ALPHATESTVALUE = "0.5";
_this.SPECULAROVERALPHA = false;
_this.RADIANCEOVERALPHA = false;
_this.ALPHAFRESNEL = false;
_this.LINEARALPHAFRESNEL = false;
_this.PREMULTIPLYALPHA = false;
_this.EMISSIVE = false;
_this.EMISSIVEDIRECTUV = 0;
_this.REFLECTIVITY = false;
_this.REFLECTIVITYDIRECTUV = 0;
_this.SPECULARTERM = false;
_this.MICROSURFACEFROMREFLECTIVITYMAP = false;
_this.MICROSURFACEAUTOMATIC = false;
_this.LODBASEDMICROSFURACE = false;
_this.MICROSURFACEMAP = false;
_this.MICROSURFACEMAPDIRECTUV = 0;
_this.METALLICWORKFLOW = false;
_this.ROUGHNESSSTOREINMETALMAPALPHA = false;
_this.ROUGHNESSSTOREINMETALMAPGREEN = false;
_this.METALLNESSSTOREINMETALMAPBLUE = false;
_this.AOSTOREINMETALMAPRED = false;
_this.ENVIRONMENTBRDF = false;
_this.NORMAL = false;
_this.TANGENT = false;
_this.BUMP = false;
_this.BUMPDIRECTUV = 0;
_this.OBJECTSPACE_NORMALMAP = false;
_this.PARALLAX = false;
_this.PARALLAXOCCLUSION = false;
_this.NORMALXYSCALE = true;
_this.LIGHTMAP = false;
_this.LIGHTMAPDIRECTUV = 0;
_this.USELIGHTMAPASSHADOWMAP = false;
_this.GAMMALIGHTMAP = false;
_this.REFLECTION = false;
_this.REFLECTIONMAP_3D = false;
_this.REFLECTIONMAP_SPHERICAL = false;
_this.REFLECTIONMAP_PLANAR = false;
_this.REFLECTIONMAP_CUBIC = false;
_this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
_this.REFLECTIONMAP_PROJECTION = false;
_this.REFLECTIONMAP_SKYBOX = false;
_this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
_this.REFLECTIONMAP_EXPLICIT = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
_this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
_this.INVERTCUBICMAP = false;
_this.USESPHERICALFROMREFLECTIONMAP = false;
_this.USESPHERICALINVERTEX = false;
_this.REFLECTIONMAP_OPPOSITEZ = false;
_this.LODINREFLECTIONALPHA = false;
_this.GAMMAREFLECTION = false;
_this.RGBDREFLECTION = false;
_this.RADIANCEOCCLUSION = false;
_this.HORIZONOCCLUSION = false;
_this.REFRACTION = false;
_this.REFRACTIONMAP_3D = false;
_this.REFRACTIONMAP_OPPOSITEZ = false;
_this.LODINREFRACTIONALPHA = false;
_this.GAMMAREFRACTION = false;
_this.RGBDREFRACTION = false;
_this.LINKREFRACTIONTOTRANSPARENCY = false;
_this.INSTANCES = false;
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.NONUNIFORMSCALING = false;
_this.MORPHTARGETS = false;
_this.MORPHTARGETS_NORMAL = false;
_this.MORPHTARGETS_TANGENT = false;
_this.NUM_MORPH_INFLUENCERS = 0;
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.TONEMAPPING_ACES = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.EXPOSURE = false;
_this.USEPHYSICALLIGHTFALLOFF = false;
_this.USEGLTFLIGHTFALLOFF = false;
_this.TWOSIDEDLIGHTING = false;
_this.SHADOWFLOAT = false;
_this.CLIPPLANE = false;
_this.CLIPPLANE2 = false;
_this.CLIPPLANE3 = false;
_this.CLIPPLANE4 = false;
_this.POINTSIZE = false;
_this.FOG = false;
_this.LOGARITHMICDEPTH = false;
_this.FORCENORMALFORWARD = false;
_this.SPECULARAA = false;
_this.UNLIT = false;
_this.rebuild();
return _this;
}
PBRMaterialDefines2.prototype.reset = function() {
_super.prototype.reset.call(this);
this.ALPHATESTVALUE = "0.5";
this.PBR = true;
};
return PBRMaterialDefines2;
}(BABYLON2.MaterialDefines)
);
var PBRBaseMaterial = (
/** @class */
function(_super) {
__extends(PBRBaseMaterial2, _super);
function PBRBaseMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._directIntensity = 1;
_this._emissiveIntensity = 1;
_this._environmentIntensity = 1;
_this._specularIntensity = 1;
_this._lightingInfos = new BABYLON2.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
_this._disableBumpMap = false;
_this._ambientTextureStrength = 1;
_this._ambientTextureImpactOnAnalyticalLights = BABYLON2.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
_this._ambientColor = new BABYLON2.Color3(0, 0, 0);
_this._albedoColor = new BABYLON2.Color3(1, 1, 1);
_this._reflectivityColor = new BABYLON2.Color3(1, 1, 1);
_this._reflectionColor = new BABYLON2.Color3(1, 1, 1);
_this._emissiveColor = new BABYLON2.Color3(0, 0, 0);
_this._microSurface = 0.9;
_this._indexOfRefraction = 0.66;
_this._invertRefractionY = false;
_this._linkRefractionWithTransparency = false;
_this._useLightmapAsShadowmap = false;
_this._useHorizonOcclusion = true;
_this._useRadianceOcclusion = true;
_this._useAlphaFromAlbedoTexture = false;
_this._useSpecularOverAlpha = true;
_this._useMicroSurfaceFromReflectivityMapAlpha = false;
_this._useRoughnessFromMetallicTextureAlpha = true;
_this._useRoughnessFromMetallicTextureGreen = false;
_this._useMetallnessFromMetallicTextureBlue = false;
_this._useAmbientOcclusionFromMetallicTextureRed = false;
_this._useAmbientInGrayScale = false;
_this._useAutoMicroSurfaceFromReflectivityMap = false;
_this._lightFalloff = PBRBaseMaterial2.LIGHTFALLOFF_PHYSICAL;
_this._useRadianceOverAlpha = true;
_this._useObjectSpaceNormalMap = false;
_this._useParallax = false;
_this._useParallaxOcclusion = false;
_this._parallaxScaleBias = 0.05;
_this._disableLighting = false;
_this._maxSimultaneousLights = 4;
_this._invertNormalMapX = false;
_this._invertNormalMapY = false;
_this._twoSidedLighting = false;
_this._alphaCutOff = 0.4;
_this._forceAlphaTest = false;
_this._useAlphaFresnel = false;
_this._useLinearAlphaFresnel = false;
_this._transparencyMode = null;
_this._environmentBRDFTexture = null;
_this._forceIrradianceInFragment = false;
_this._forceNormalForward = false;
_this._enableSpecularAntiAliasing = false;
_this._renderTargets = new BABYLON2.SmartArray(16);
_this._globalAmbientColor = new BABYLON2.Color3(0, 0, 0);
_this._unlit = false;
_this._attachImageProcessingConfiguration(null);
_this.getRenderTargetTextures = function() {
_this._renderTargets.reset();
if (BABYLON2.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
_this._renderTargets.push(_this._reflectionTexture);
}
if (BABYLON2.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
_this._renderTargets.push(_this._refractionTexture);
}
return _this._renderTargets;
};
_this._environmentBRDFTexture = BABYLON2.TextureTools.GetEnvironmentBRDFTexture(scene);
return _this;
}
PBRBaseMaterial2.prototype._attachImageProcessingConfiguration = function(configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
} else {
this._imageProcessingConfiguration = configuration;
}
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function(conf) {
_this._markAllSubMeshesAsImageProcessingDirty();
});
}
};
Object.defineProperty(PBRBaseMaterial2.prototype, "hasRenderTargetTextures", {
/**
* Gets a boolean indicating that current material needs to register RTT
*/
get: function() {
if (BABYLON2.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
return true;
}
if (BABYLON2.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
return true;
}
return false;
},
enumerable: true,
configurable: true
});
PBRBaseMaterial2.prototype.getClassName = function() {
return "PBRBaseMaterial";
};
Object.defineProperty(PBRBaseMaterial2.prototype, "useLogarithmicDepth", {
/**
* Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
*/
get: function() {
return this._useLogarithmicDepth;
},
/**
* Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
*/
set: function(value) {
this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRBaseMaterial2.prototype, "transparencyMode", {
/**
* Gets the current transparency mode.
*/
get: function() {
return this._transparencyMode;
},
/**
* Sets the transparency mode of the material.
*
* | Value | Type | Description |
* | ----- | ----------------------------------- | ----------- |
* | 0 | OPAQUE | |
* | 1 | ALPHATEST | |
* | 2 | ALPHABLEND | |
* | 3 | ALPHATESTANDBLEND | |
*
*/
set: function(value) {
if (this._transparencyMode === value) {
return;
}
this._transparencyMode = value;
this._forceAlphaTest = value === BABYLON2.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND;
this._markAllSubMeshesAsTexturesAndMiscDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRBaseMaterial2.prototype, "_disableAlphaBlending", {
/**
* Returns true if alpha blending should be disabled.
*/
get: function() {
return this._linkRefractionWithTransparency || this._transparencyMode === BABYLON2.PBRMaterial.PBRMATERIAL_OPAQUE || this._transparencyMode === BABYLON2.PBRMaterial.PBRMATERIAL_ALPHATEST;
},
enumerable: true,
configurable: true
});
PBRBaseMaterial2.prototype.needAlphaBlending = function() {
if (this._disableAlphaBlending) {
return false;
}
return this.alpha < 1 || this._opacityTexture != null || this._shouldUseAlphaFromAlbedoTexture();
};
PBRBaseMaterial2.prototype.needAlphaBlendingForMesh = function(mesh2) {
if (this._disableAlphaBlending) {
return false;
}
return _super.prototype.needAlphaBlendingForMesh.call(this, mesh2);
};
PBRBaseMaterial2.prototype.needAlphaTesting = function() {
if (this._forceAlphaTest) {
return true;
}
if (this._linkRefractionWithTransparency) {
return false;
}
return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON2.PBRMaterial.PBRMATERIAL_ALPHATEST);
};
PBRBaseMaterial2.prototype._shouldUseAlphaFromAlbedoTexture = function() {
return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON2.PBRMaterial.PBRMATERIAL_OPAQUE;
};
PBRBaseMaterial2.prototype.getAlphaTestTexture = function() {
return this._albedoTexture;
};
PBRBaseMaterial2.prototype.isReadyForSubMesh = function(mesh2, subMesh, useInstances) {
if (subMesh.effect && this.isFrozen) {
if (this._wasPreviouslyReady) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new PBRMaterialDefines();
}
var defines = subMesh._materialDefines;
if (!this.checkReadyOnEveryCall && subMesh.effect) {
if (defines._renderId === this.getScene().getRenderId()) {
return true;
}
}
var scene = this.getScene();
var engine = scene.getEngine();
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._albedoTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
if (!this._albedoTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._ambientTexture && BABYLON2.StandardMaterial.AmbientTextureEnabled) {
if (!this._ambientTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._opacityTexture && BABYLON2.StandardMaterial.OpacityTextureEnabled) {
if (!this._opacityTexture.isReadyOrNotBlocking()) {
return false;
}
}
var reflectionTexture = this._getReflectionTexture();
if (reflectionTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
if (!reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._lightmapTexture && BABYLON2.StandardMaterial.LightmapTextureEnabled) {
if (!this._lightmapTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._emissiveTexture && BABYLON2.StandardMaterial.EmissiveTextureEnabled) {
if (!this._emissiveTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (BABYLON2.StandardMaterial.SpecularTextureEnabled) {
if (this._metallicTexture) {
if (!this._metallicTexture.isReadyOrNotBlocking()) {
return false;
}
} else if (this._reflectivityTexture) {
if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._microSurfaceTexture) {
if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
return false;
}
}
}
if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON2.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
if (!this._bumpTexture.isReady()) {
return false;
}
}
var refractionTexture = this._getRefractionTexture();
if (refractionTexture && BABYLON2.StandardMaterial.RefractionTextureEnabled) {
if (!refractionTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._environmentBRDFTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
if (!this._environmentBRDFTexture.isReady()) {
return false;
}
}
}
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
}
if (!engine.getCaps().standardDerivatives && !mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
mesh2.createNormals(true);
BABYLON2.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh2.name);
}
var effect = this._prepareEffect(mesh2, defines, this.onCompiled, this.onError, useInstances);
if (effect) {
scene.resetCachedMaterial();
subMesh.setEffect(effect, defines);
this.buildUniformLayout();
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
this._wasPreviouslyReady = true;
return true;
};
PBRBaseMaterial2.prototype.isMetallicWorkflow = function() {
if (this._metallic != null || this._roughness != null || this._metallicTexture) {
return true;
}
return false;
};
PBRBaseMaterial2.prototype._prepareEffect = function(mesh2, defines, onCompiled, onError, useInstances, useClipPlane) {
if (onCompiled === void 0) {
onCompiled = null;
}
if (onError === void 0) {
onError = null;
}
if (useInstances === void 0) {
useInstances = null;
}
if (useClipPlane === void 0) {
useClipPlane = null;
}
this._prepareDefines(mesh2, defines, useInstances, useClipPlane);
if (!defines.isDirty) {
return null;
}
defines.markAsProcessed();
var scene = this.getScene();
var engine = scene.getEngine();
var fallbacks = new BABYLON2.EffectFallbacks();
var fallbackRank = 0;
if (defines.USESPHERICALINVERTEX) {
fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
}
if (defines.FOG) {
fallbacks.addFallback(fallbackRank, "FOG");
}
if (defines.SPECULARAA) {
fallbacks.addFallback(fallbackRank, "SPECULARAA");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(fallbackRank, "POINTSIZE");
}
if (defines.LOGARITHMICDEPTH) {
fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
}
if (defines.PARALLAX) {
fallbacks.addFallback(fallbackRank, "PARALLAX");
}
if (defines.PARALLAXOCCLUSION) {
fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
}
if (defines.ENVIRONMENTBRDF) {
fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
}
if (defines.TANGENT) {
fallbacks.addFallback(fallbackRank++, "TANGENT");
}
if (defines.BUMP) {
fallbacks.addFallback(fallbackRank++, "BUMP");
}
fallbackRank = BABYLON2.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
if (defines.SPECULARTERM) {
fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
}
if (defines.USESPHERICALFROMREFLECTIONMAP) {
fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
}
if (defines.LIGHTMAP) {
fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
}
if (defines.NORMAL) {
fallbacks.addFallback(fallbackRank++, "NORMAL");
}
if (defines.AMBIENT) {
fallbacks.addFallback(fallbackRank++, "AMBIENT");
}
if (defines.EMISSIVE) {
fallbacks.addFallback(fallbackRank++, "EMISSIVE");
}
if (defines.VERTEXCOLOR) {
fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
}
if (defines.NUM_BONE_INFLUENCERS > 0) {
fallbacks.addCPUSkinningFallback(fallbackRank++, mesh2);
}
if (defines.MORPHTARGETS) {
fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
}
var attribs = [BABYLON2.VertexBuffer.PositionKind];
if (defines.NORMAL) {
attribs.push(BABYLON2.VertexBuffer.NormalKind);
}
if (defines.TANGENT) {
attribs.push(BABYLON2.VertexBuffer.TangentKind);
}
if (defines.UV1) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
}
if (defines.UV2) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
}
if (defines.VERTEXCOLOR) {
attribs.push(BABYLON2.VertexBuffer.ColorKind);
}
BABYLON2.MaterialHelper.PrepareAttributesForBones(attribs, mesh2, defines, fallbacks);
BABYLON2.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
BABYLON2.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh2, defines);
var uniforms = [
"world",
"view",
"viewProjection",
"vEyePosition",
"vLightsType",
"vAmbientColor",
"vAlbedoColor",
"vReflectivityColor",
"vEmissiveColor",
"vReflectionColor",
"vFogInfos",
"vFogColor",
"pointSize",
"vAlbedoInfos",
"vAmbientInfos",
"vOpacityInfos",
"vReflectionInfos",
"vReflectionPosition",
"vReflectionSize",
"vEmissiveInfos",
"vReflectivityInfos",
"vMicroSurfaceSamplerInfos",
"vBumpInfos",
"vLightmapInfos",
"vRefractionInfos",
"mBones",
"vClipPlane",
"vClipPlane2",
"vClipPlane3",
"vClipPlane4",
"albedoMatrix",
"ambientMatrix",
"opacityMatrix",
"reflectionMatrix",
"emissiveMatrix",
"reflectivityMatrix",
"normalMatrix",
"microSurfaceSamplerMatrix",
"bumpMatrix",
"lightmapMatrix",
"refractionMatrix",
"vLightingIntensity",
"logarithmicDepthConstant",
"vSphericalX",
"vSphericalY",
"vSphericalZ",
"vSphericalXX",
"vSphericalYY",
"vSphericalZZ",
"vSphericalXY",
"vSphericalYZ",
"vSphericalZX",
"vReflectionMicrosurfaceInfos",
"vRefractionMicrosurfaceInfos",
"vTangentSpaceParams"
];
var samplers = [
"albedoSampler",
"reflectivitySampler",
"ambientSampler",
"emissiveSampler",
"bumpSampler",
"lightmapSampler",
"opacitySampler",
"refractionSampler",
"refractionSamplerLow",
"refractionSamplerHigh",
"reflectionSampler",
"reflectionSamplerLow",
"reflectionSamplerHigh",
"microSurfaceSampler",
"environmentBrdfSampler"
];
var uniformBuffers = ["Material", "Scene"];
if (BABYLON2.ImageProcessingConfiguration) {
BABYLON2.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
BABYLON2.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
}
BABYLON2.MaterialHelper.PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers,
defines,
maxSimultaneousLights: this._maxSimultaneousLights
});
var join = defines.toString();
return engine.createEffect("pbr", {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers,
defines: join,
fallbacks,
onCompiled,
onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
}, engine);
};
PBRBaseMaterial2.prototype._prepareDefines = function(mesh2, defines, useInstances, useClipPlane) {
if (useInstances === void 0) {
useInstances = null;
}
if (useClipPlane === void 0) {
useClipPlane = null;
}
var scene = this.getScene();
var engine = scene.getEngine();
BABYLON2.MaterialHelper.PrepareDefinesForLights(scene, mesh2, defines, true, this._maxSimultaneousLights, this._disableLighting);
defines._needNormals = true;
defines.METALLICWORKFLOW = this.isMetallicWorkflow();
if (defines._areTexturesDirty) {
defines._needUVs = false;
if (scene.texturesEnabled) {
if (scene.getEngine().getCaps().textureLOD) {
defines.LODBASEDMICROSFURACE = true;
}
if (this._albedoTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
} else {
defines.ALBEDO = false;
}
if (this._ambientTexture && BABYLON2.StandardMaterial.AmbientTextureEnabled) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
} else {
defines.AMBIENT = false;
}
if (this._opacityTexture && BABYLON2.StandardMaterial.OpacityTextureEnabled) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
} else {
defines.OPACITY = false;
}
var reflectionTexture = this._getReflectionTexture();
if (reflectionTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
defines.REFLECTION = true;
defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
defines.RGBDREFLECTION = reflectionTexture.isRGBD;
defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
if (reflectionTexture.coordinatesMode === BABYLON2.Texture.INVCUBIC_MODE) {
defines.INVERTCUBICMAP = true;
}
defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
switch (reflectionTexture.coordinatesMode) {
case BABYLON2.Texture.EXPLICIT_MODE:
defines.REFLECTIONMAP_EXPLICIT = true;
break;
case BABYLON2.Texture.PLANAR_MODE:
defines.REFLECTIONMAP_PLANAR = true;
break;
case BABYLON2.Texture.PROJECTION_MODE:
defines.REFLECTIONMAP_PROJECTION = true;
break;
case BABYLON2.Texture.SKYBOX_MODE:
defines.REFLECTIONMAP_SKYBOX = true;
break;
case BABYLON2.Texture.SPHERICAL_MODE:
defines.REFLECTIONMAP_SPHERICAL = true;
break;
case BABYLON2.Texture.EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
break;
case BABYLON2.Texture.FIXED_EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
break;
case BABYLON2.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
break;
case BABYLON2.Texture.CUBIC_MODE:
case BABYLON2.Texture.INVCUBIC_MODE:
default:
defines.REFLECTIONMAP_CUBIC = true;
defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
break;
}
if (reflectionTexture.coordinatesMode !== BABYLON2.Texture.SKYBOX_MODE) {
if (reflectionTexture.sphericalPolynomial) {
defines.USESPHERICALFROMREFLECTIONMAP = true;
if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
defines.USESPHERICALINVERTEX = false;
} else {
defines.USESPHERICALINVERTEX = true;
}
}
} else {
defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
}
} else {
defines.REFLECTION = false;
defines.REFLECTIONMAP_3D = false;
defines.REFLECTIONMAP_SPHERICAL = false;
defines.REFLECTIONMAP_PLANAR = false;
defines.REFLECTIONMAP_CUBIC = false;
defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
defines.REFLECTIONMAP_PROJECTION = false;
defines.REFLECTIONMAP_SKYBOX = false;
defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
defines.REFLECTIONMAP_EXPLICIT = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
defines.INVERTCUBICMAP = false;
defines.USESPHERICALFROMREFLECTIONMAP = false;
defines.USESPHERICALINVERTEX = false;
defines.REFLECTIONMAP_OPPOSITEZ = false;
defines.LODINREFLECTIONALPHA = false;
defines.GAMMAREFLECTION = false;
defines.RGBDREFLECTION = false;
}
if (this._lightmapTexture && BABYLON2.StandardMaterial.LightmapTextureEnabled) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
} else {
defines.LIGHTMAP = false;
}
if (this._emissiveTexture && BABYLON2.StandardMaterial.EmissiveTextureEnabled) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
} else {
defines.EMISSIVE = false;
}
if (BABYLON2.StandardMaterial.SpecularTextureEnabled) {
if (this._metallicTexture) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
} else if (this._reflectivityTexture) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
} else {
defines.REFLECTIVITY = false;
}
if (this._microSurfaceTexture) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
} else {
defines.MICROSURFACEMAP = false;
}
} else {
defines.REFLECTIVITY = false;
defines.MICROSURFACEMAP = false;
}
if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON2.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
if (this._useParallax && this._albedoTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
defines.PARALLAX = true;
defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
} else {
defines.PARALLAX = false;
}
defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
} else {
defines.BUMP = false;
}
var refractionTexture = this._getRefractionTexture();
if (refractionTexture && BABYLON2.StandardMaterial.RefractionTextureEnabled) {
defines.REFRACTION = true;
defines.REFRACTIONMAP_3D = refractionTexture.isCube;
defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
defines.RGBDREFRACTION = refractionTexture.isRGBD;
defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
if (this._linkRefractionWithTransparency) {
defines.LINKREFRACTIONTOTRANSPARENCY = true;
}
} else {
defines.REFRACTION = false;
}
if (this._environmentBRDFTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
defines.ENVIRONMENTBRDF = true;
} else {
defines.ENVIRONMENTBRDF = false;
}
if (this._shouldUseAlphaFromAlbedoTexture()) {
defines.ALPHAFROMALBEDO = true;
} else {
defines.ALPHAFROMALBEDO = false;
}
}
defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
if (this._lightFalloff === PBRBaseMaterial2.LIGHTFALLOFF_STANDARD) {
defines.USEPHYSICALLIGHTFALLOFF = false;
defines.USEGLTFLIGHTFALLOFF = false;
} else if (this._lightFalloff === PBRBaseMaterial2.LIGHTFALLOFF_GLTF) {
defines.USEPHYSICALLIGHTFALLOFF = false;
defines.USEGLTFLIGHTFALLOFF = true;
} else {
defines.USEPHYSICALLIGHTFALLOFF = true;
defines.USEGLTFLIGHTFALLOFF = false;
}
defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
if (!this.backFaceCulling && this._twoSidedLighting) {
defines.TWOSIDEDLIGHTING = true;
} else {
defines.TWOSIDEDLIGHTING = false;
}
defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
defines.PREMULTIPLYALPHA = this.alphaMode === BABYLON2.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON2.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh2);
defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
this._imageProcessingConfiguration.prepareDefines(defines);
}
defines.FORCENORMALFORWARD = this._forceNormalForward;
defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
if (defines._areMiscDirty) {
BABYLON2.MaterialHelper.PrepareDefinesForMisc(mesh2, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh2) || this._forceAlphaTest, defines);
defines.UNLIT = this._unlit || (this.pointsCloud || this.wireframe) && !mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind);
}
BABYLON2.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
BABYLON2.MaterialHelper.PrepareDefinesForAttributes(mesh2, defines, true, true, true, this._transparencyMode !== BABYLON2.PBRMaterial.PBRMATERIAL_OPAQUE);
};
PBRBaseMaterial2.prototype.forceCompilation = function(mesh2, onCompiled, options) {
var _this = this;
var localOptions = __assign({ clipPlane: false }, options);
var defines = new PBRMaterialDefines();
var effect = this._prepareEffect(mesh2, defines, void 0, void 0, void 0, localOptions.clipPlane);
if (effect.isReady()) {
if (onCompiled) {
onCompiled(this);
}
} else {
effect.onCompileObservable.add(function() {
if (onCompiled) {
onCompiled(_this);
}
});
}
};
PBRBaseMaterial2.prototype.buildUniformLayout = function() {
this._uniformBuffer.addUniform("vAlbedoInfos", 2);
this._uniformBuffer.addUniform("vAmbientInfos", 4);
this._uniformBuffer.addUniform("vOpacityInfos", 2);
this._uniformBuffer.addUniform("vEmissiveInfos", 2);
this._uniformBuffer.addUniform("vLightmapInfos", 2);
this._uniformBuffer.addUniform("vReflectivityInfos", 3);
this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
this._uniformBuffer.addUniform("vRefractionInfos", 4);
this._uniformBuffer.addUniform("vReflectionInfos", 2);
this._uniformBuffer.addUniform("vReflectionPosition", 3);
this._uniformBuffer.addUniform("vReflectionSize", 3);
this._uniformBuffer.addUniform("vBumpInfos", 3);
this._uniformBuffer.addUniform("albedoMatrix", 16);
this._uniformBuffer.addUniform("ambientMatrix", 16);
this._uniformBuffer.addUniform("opacityMatrix", 16);
this._uniformBuffer.addUniform("emissiveMatrix", 16);
this._uniformBuffer.addUniform("lightmapMatrix", 16);
this._uniformBuffer.addUniform("reflectivityMatrix", 16);
this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
this._uniformBuffer.addUniform("bumpMatrix", 16);
this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
this._uniformBuffer.addUniform("refractionMatrix", 16);
this._uniformBuffer.addUniform("reflectionMatrix", 16);
this._uniformBuffer.addUniform("vReflectionColor", 3);
this._uniformBuffer.addUniform("vAlbedoColor", 4);
this._uniformBuffer.addUniform("vLightingIntensity", 4);
this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
this._uniformBuffer.addUniform("vReflectivityColor", 4);
this._uniformBuffer.addUniform("vEmissiveColor", 3);
this._uniformBuffer.addUniform("pointSize", 1);
this._uniformBuffer.create();
};
PBRBaseMaterial2.prototype.unbind = function() {
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._uniformBuffer.setTexture("reflectionSampler", null);
}
if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
this._uniformBuffer.setTexture("refractionSampler", null);
}
_super.prototype.unbind.call(this);
};
PBRBaseMaterial2.prototype.bindForSubMesh = function(world, mesh2, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
this.bindOnlyWorldMatrix(world);
if (defines.OBJECTSPACE_NORMALMAP) {
world.toNormalMatrix(this._normalMatrix);
this.bindOnlyNormalMatrix(this._normalMatrix);
}
var mustRebind = this._mustRebind(scene, effect, mesh2.visibility);
BABYLON2.MaterialHelper.BindBonesParameters(mesh2, this._activeEffect);
var reflectionTexture = null;
if (mustRebind) {
this._uniformBuffer.bindToEffect(effect, "Material");
this.bindViewProjection(effect);
reflectionTexture = this._getReflectionTexture();
var refractionTexture = this._getRefractionTexture();
if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
if (scene.texturesEnabled) {
if (this._albedoTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
}
if (this._ambientTexture && BABYLON2.StandardMaterial.AmbientTextureEnabled) {
this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
BABYLON2.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
}
if (this._opacityTexture && BABYLON2.StandardMaterial.OpacityTextureEnabled) {
this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
}
if (reflectionTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
if (reflectionTexture.boundingBoxSize) {
var cubeTexture = reflectionTexture;
this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
}
var polynomials = reflectionTexture.sphericalPolynomial;
if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
}
this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
}
if (this._emissiveTexture && BABYLON2.StandardMaterial.EmissiveTextureEnabled) {
this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
}
if (this._lightmapTexture && BABYLON2.StandardMaterial.LightmapTextureEnabled) {
this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
}
if (BABYLON2.StandardMaterial.SpecularTextureEnabled) {
if (this._metallicTexture) {
this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
BABYLON2.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
} else if (this._reflectivityTexture) {
this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1);
BABYLON2.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
}
if (this._microSurfaceTexture) {
this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
}
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON2.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
BABYLON2.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
if (scene._mirroredCameraPosition) {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1);
} else {
this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1);
}
}
if (refractionTexture && BABYLON2.StandardMaterial.RefractionTextureEnabled) {
this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
var depth = 1;
if (!refractionTexture.isCube) {
if (refractionTexture.depth) {
depth = refractionTexture.depth;
}
}
this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
}
}
if (this.pointsCloud) {
this._uniformBuffer.updateFloat("pointSize", this.pointSize);
}
if (defines.METALLICWORKFLOW) {
BABYLON2.PBRMaterial._scaledReflectivity.r = this._metallic === void 0 || this._metallic === null ? 1 : this._metallic;
BABYLON2.PBRMaterial._scaledReflectivity.g = this._roughness === void 0 || this._roughness === null ? 1 : this._roughness;
this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON2.PBRMaterial._scaledReflectivity, 0);
} else {
this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
}
this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh2.visibility);
this._lightingInfos.x = this._directIntensity;
this._lightingInfos.y = this._emissiveIntensity;
this._lightingInfos.z = this._environmentIntensity;
this._lightingInfos.w = this._specularIntensity;
this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
}
if (scene.texturesEnabled) {
if (this._albedoTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
}
if (this._ambientTexture && BABYLON2.StandardMaterial.AmbientTextureEnabled) {
this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
}
if (this._opacityTexture && BABYLON2.StandardMaterial.OpacityTextureEnabled) {
this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
}
if (reflectionTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
if (defines.LODBASEDMICROSFURACE) {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
} else {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
}
}
if (defines.ENVIRONMENTBRDF) {
this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
}
if (refractionTexture && BABYLON2.StandardMaterial.RefractionTextureEnabled) {
if (defines.LODBASEDMICROSFURACE) {
this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
} else {
this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
}
}
if (this._emissiveTexture && BABYLON2.StandardMaterial.EmissiveTextureEnabled) {
this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
}
if (this._lightmapTexture && BABYLON2.StandardMaterial.LightmapTextureEnabled) {
this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
}
if (BABYLON2.StandardMaterial.SpecularTextureEnabled) {
if (this._metallicTexture) {
this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
} else if (this._reflectivityTexture) {
this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
}
if (this._microSurfaceTexture) {
this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
}
}
if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON2.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
}
}
BABYLON2.MaterialHelper.BindClipPlane(this._activeEffect, scene);
scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
var invertNormal = scene.useRightHandedSystem === (scene._mirroredCameraPosition != null);
effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
effect.setColor3("vAmbientColor", this._globalAmbientColor);
}
if (mustRebind || !this.isFrozen) {
if (scene.lightsEnabled && !this._disableLighting) {
BABYLON2.MaterialHelper.BindLights(scene, mesh2, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial2.LIGHTFALLOFF_STANDARD);
}
if (scene.fogEnabled && mesh2.applyFog && scene.fogMode !== BABYLON2.Scene.FOGMODE_NONE || reflectionTexture) {
this.bindView(effect);
}
BABYLON2.MaterialHelper.BindFogParameters(scene, mesh2, this._activeEffect, true);
if (defines.NUM_MORPH_INFLUENCERS) {
BABYLON2.MaterialHelper.BindMorphTargetParameters(mesh2, this._activeEffect);
}
this._imageProcessingConfiguration.bind(this._activeEffect);
BABYLON2.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
}
this._uniformBuffer.update();
this._afterBind(mesh2, this._activeEffect);
};
PBRBaseMaterial2.prototype.getAnimatables = function() {
var results = [];
if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
results.push(this._albedoTexture);
}
if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
results.push(this._ambientTexture);
}
if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
results.push(this._opacityTexture);
}
if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
results.push(this._reflectionTexture);
}
if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
results.push(this._emissiveTexture);
}
if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
results.push(this._metallicTexture);
} else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
results.push(this._reflectivityTexture);
}
if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
results.push(this._bumpTexture);
}
if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
results.push(this._lightmapTexture);
}
if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
results.push(this._refractionTexture);
}
return results;
};
PBRBaseMaterial2.prototype._getReflectionTexture = function() {
if (this._reflectionTexture) {
return this._reflectionTexture;
}
return this.getScene().environmentTexture;
};
PBRBaseMaterial2.prototype._getRefractionTexture = function() {
if (this._refractionTexture) {
return this._refractionTexture;
}
if (this._linkRefractionWithTransparency) {
return this.getScene().environmentTexture;
}
return null;
};
PBRBaseMaterial2.prototype.dispose = function(forceDisposeEffect, forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._albedoTexture) {
this._albedoTexture.dispose();
}
if (this._ambientTexture) {
this._ambientTexture.dispose();
}
if (this._opacityTexture) {
this._opacityTexture.dispose();
}
if (this._reflectionTexture) {
this._reflectionTexture.dispose();
}
if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
this._environmentBRDFTexture.dispose();
}
if (this._emissiveTexture) {
this._emissiveTexture.dispose();
}
if (this._metallicTexture) {
this._metallicTexture.dispose();
}
if (this._reflectivityTexture) {
this._reflectivityTexture.dispose();
}
if (this._bumpTexture) {
this._bumpTexture.dispose();
}
if (this._lightmapTexture) {
this._lightmapTexture.dispose();
}
if (this._refractionTexture) {
this._refractionTexture.dispose();
}
}
this._renderTargets.dispose();
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
};
PBRBaseMaterial2.LIGHTFALLOFF_PHYSICAL = 0;
PBRBaseMaterial2.LIGHTFALLOFF_GLTF = 1;
PBRBaseMaterial2.LIGHTFALLOFF_STANDARD = 2;
PBRBaseMaterial2._scaledReflectivity = new BABYLON2.Color3();
__decorate([
BABYLON2.serializeAsImageProcessingConfiguration()
], PBRBaseMaterial2.prototype, "_imageProcessingConfiguration", void 0);
__decorate([
BABYLON2.serialize()
], PBRBaseMaterial2.prototype, "useLogarithmicDepth", null);
__decorate([
BABYLON2.serialize()
], PBRBaseMaterial2.prototype, "transparencyMode", null);
return PBRBaseMaterial2;
}(BABYLON2.PushMaterial)
);
BABYLON2.PBRBaseMaterial = PBRBaseMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PBRBaseSimpleMaterial = (
/** @class */
function(_super) {
__extends(PBRBaseSimpleMaterial2, _super);
function PBRBaseSimpleMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.maxSimultaneousLights = 4;
_this.disableLighting = false;
_this.invertNormalMapX = false;
_this.invertNormalMapY = false;
_this.emissiveColor = new BABYLON2.Color3(0, 0, 0);
_this.occlusionStrength = 1;
_this.useLightmapAsShadowmap = false;
_this._useAlphaFromAlbedoTexture = true;
_this._useAmbientInGrayScale = true;
return _this;
}
Object.defineProperty(PBRBaseSimpleMaterial2.prototype, "doubleSided", {
/**
* Gets the current double sided mode.
*/
get: function() {
return this._twoSidedLighting;
},
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
set: function(value) {
if (this._twoSidedLighting === value) {
return;
}
this._twoSidedLighting = value;
this.backFaceCulling = !value;
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
PBRBaseSimpleMaterial2.prototype.getActiveTextures = function() {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this.environmentTexture) {
activeTextures.push(this.environmentTexture);
}
if (this.normalTexture) {
activeTextures.push(this.normalTexture);
}
if (this.emissiveTexture) {
activeTextures.push(this.emissiveTexture);
}
if (this.occlusionTexture) {
activeTextures.push(this.occlusionTexture);
}
if (this.lightmapTexture) {
activeTextures.push(this.lightmapTexture);
}
return activeTextures;
};
PBRBaseSimpleMaterial2.prototype.hasTexture = function(texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this.lightmapTexture === texture) {
return true;
}
return false;
};
PBRBaseSimpleMaterial2.prototype.getClassName = function() {
return "PBRBaseSimpleMaterial";
};
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial2.prototype, "maxSimultaneousLights", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial2.prototype, "disableLighting", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
], PBRBaseSimpleMaterial2.prototype, "environmentTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial2.prototype, "invertNormalMapX", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial2.prototype, "invertNormalMapY", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
], PBRBaseSimpleMaterial2.prototype, "normalTexture", void 0);
__decorate([
BABYLON2.serializeAsColor3("emissive"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial2.prototype, "emissiveColor", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial2.prototype, "emissiveTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
], PBRBaseSimpleMaterial2.prototype, "occlusionStrength", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
], PBRBaseSimpleMaterial2.prototype, "occlusionTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
], PBRBaseSimpleMaterial2.prototype, "alphaCutOff", void 0);
__decorate([
BABYLON2.serialize()
], PBRBaseSimpleMaterial2.prototype, "doubleSided", null);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
], PBRBaseSimpleMaterial2.prototype, "lightmapTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial2.prototype, "useLightmapAsShadowmap", void 0);
return PBRBaseSimpleMaterial2;
}(BABYLON2.PBRBaseMaterial)
);
BABYLON2.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PBRMaterial = (
/** @class */
function(_super) {
__extends(PBRMaterial2, _super);
function PBRMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.directIntensity = 1;
_this.emissiveIntensity = 1;
_this.environmentIntensity = 1;
_this.specularIntensity = 1;
_this.disableBumpMap = false;
_this.ambientTextureStrength = 1;
_this.ambientTextureImpactOnAnalyticalLights = PBRMaterial2.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
_this.ambientColor = new BABYLON2.Color3(0, 0, 0);
_this.albedoColor = new BABYLON2.Color3(1, 1, 1);
_this.reflectivityColor = new BABYLON2.Color3(1, 1, 1);
_this.reflectionColor = new BABYLON2.Color3(1, 1, 1);
_this.emissiveColor = new BABYLON2.Color3(0, 0, 0);
_this.microSurface = 1;
_this.indexOfRefraction = 0.66;
_this.invertRefractionY = false;
_this.linkRefractionWithTransparency = false;
_this.useLightmapAsShadowmap = false;
_this.useAlphaFromAlbedoTexture = false;
_this.forceAlphaTest = false;
_this.alphaCutOff = 0.4;
_this.useSpecularOverAlpha = true;
_this.useMicroSurfaceFromReflectivityMapAlpha = false;
_this.useRoughnessFromMetallicTextureAlpha = true;
_this.useRoughnessFromMetallicTextureGreen = false;
_this.useMetallnessFromMetallicTextureBlue = false;
_this.useAmbientOcclusionFromMetallicTextureRed = false;
_this.useAmbientInGrayScale = false;
_this.useAutoMicroSurfaceFromReflectivityMap = false;
_this.useRadianceOverAlpha = true;
_this.useObjectSpaceNormalMap = false;
_this.useParallax = false;
_this.useParallaxOcclusion = false;
_this.parallaxScaleBias = 0.05;
_this.disableLighting = false;
_this.forceIrradianceInFragment = false;
_this.maxSimultaneousLights = 4;
_this.invertNormalMapX = false;
_this.invertNormalMapY = false;
_this.twoSidedLighting = false;
_this.useAlphaFresnel = false;
_this.useLinearAlphaFresnel = false;
_this.environmentBRDFTexture = null;
_this.forceNormalForward = false;
_this.enableSpecularAntiAliasing = false;
_this.useHorizonOcclusion = true;
_this.useRadianceOcclusion = true;
_this.unlit = false;
_this._environmentBRDFTexture = BABYLON2.TextureTools.GetEnvironmentBRDFTexture(scene);
return _this;
}
Object.defineProperty(PBRMaterial2.prototype, "usePhysicalLightFalloff", {
/**
* BJS is using an harcoded light falloff based on a manually sets up range.
* In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
* This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
*/
get: function() {
return this._lightFalloff === BABYLON2.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
},
/**
* BJS is using an harcoded light falloff based on a manually sets up range.
* In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
* This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
*/
set: function(value) {
if (value !== this.usePhysicalLightFalloff) {
this._markAllSubMeshesAsTexturesDirty();
if (value) {
this._lightFalloff = BABYLON2.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
} else {
this._lightFalloff = BABYLON2.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "useGLTFLightFalloff", {
/**
* In order to support the falloff compatibility with gltf, a special mode has been added
* to reproduce the gltf light falloff.
*/
get: function() {
return this._lightFalloff === BABYLON2.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
},
/**
* In order to support the falloff compatibility with gltf, a special mode has been added
* to reproduce the gltf light falloff.
*/
set: function(value) {
if (value !== this.useGLTFLightFalloff) {
this._markAllSubMeshesAsTexturesDirty();
if (value) {
this._lightFalloff = BABYLON2.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
} else {
this._lightFalloff = BABYLON2.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function() {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function(value) {
this._attachImageProcessingConfiguration(value);
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "cameraColorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "cameraColorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "cameraToneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function() {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function(value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "cameraExposure", {
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
get: function() {
return this._imageProcessingConfiguration.exposure;
},
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
set: function(value) {
this._imageProcessingConfiguration.exposure = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "cameraContrast", {
/**
* Gets The camera contrast used on this material.
*/
get: function() {
return this._imageProcessingConfiguration.contrast;
},
/**
* Sets The camera contrast used on this material.
*/
set: function(value) {
this._imageProcessingConfiguration.contrast = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "cameraColorGradingTexture", {
/**
* Gets the Color Grading 2D Lookup Texture.
*/
get: function() {
return this._imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets the Color Grading 2D Lookup Texture.
*/
set: function(value) {
this._imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PBRMaterial2.prototype, "cameraColorCurves", {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
get: function() {
return this._imageProcessingConfiguration.colorCurves;
},
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
set: function(value) {
this._imageProcessingConfiguration.colorCurves = value;
},
enumerable: true,
configurable: true
});
PBRMaterial2.prototype.getClassName = function() {
return "PBRMaterial";
};
PBRMaterial2.prototype.getActiveTextures = function() {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this._albedoTexture) {
activeTextures.push(this._albedoTexture);
}
if (this._ambientTexture) {
activeTextures.push(this._ambientTexture);
}
if (this._opacityTexture) {
activeTextures.push(this._opacityTexture);
}
if (this._reflectionTexture) {
activeTextures.push(this._reflectionTexture);
}
if (this._emissiveTexture) {
activeTextures.push(this._emissiveTexture);
}
if (this._reflectivityTexture) {
activeTextures.push(this._reflectivityTexture);
}
if (this._metallicTexture) {
activeTextures.push(this._metallicTexture);
}
if (this._microSurfaceTexture) {
activeTextures.push(this._microSurfaceTexture);
}
if (this._bumpTexture) {
activeTextures.push(this._bumpTexture);
}
if (this._lightmapTexture) {
activeTextures.push(this._lightmapTexture);
}
if (this._refractionTexture) {
activeTextures.push(this._refractionTexture);
}
return activeTextures;
};
PBRMaterial2.prototype.hasTexture = function(texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this._albedoTexture === texture) {
return true;
}
if (this._ambientTexture === texture) {
return true;
}
if (this._opacityTexture === texture) {
return true;
}
if (this._reflectionTexture === texture) {
return true;
}
if (this._reflectivityTexture === texture) {
return true;
}
if (this._metallicTexture === texture) {
return true;
}
if (this._microSurfaceTexture === texture) {
return true;
}
if (this._bumpTexture === texture) {
return true;
}
if (this._lightmapTexture === texture) {
return true;
}
if (this._refractionTexture === texture) {
return true;
}
return false;
};
PBRMaterial2.prototype.clone = function(name) {
var _this = this;
var clone = BABYLON2.SerializationHelper.Clone(function() {
return new PBRMaterial2(name, _this.getScene());
}, this);
clone.id = name;
clone.name = name;
return clone;
};
PBRMaterial2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.PBRMaterial";
return serializationObject;
};
PBRMaterial2.Parse = function(source, scene, rootUrl) {
return BABYLON2.SerializationHelper.Parse(function() {
return new PBRMaterial2(source.name, scene);
}, source, scene, rootUrl);
};
PBRMaterial2.PBRMATERIAL_OPAQUE = 0;
PBRMaterial2.PBRMATERIAL_ALPHATEST = 1;
PBRMaterial2.PBRMATERIAL_ALPHABLEND = 2;
PBRMaterial2.PBRMATERIAL_ALPHATESTANDBLEND = 3;
PBRMaterial2.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "directIntensity", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "emissiveIntensity", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "environmentIntensity", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "specularIntensity", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "disableBumpMap", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "albedoTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "ambientTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "ambientTextureStrength", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial2.prototype, "opacityTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "reflectionTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "emissiveTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "reflectivityTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "metallicTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "metallic", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "roughness", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "microSurfaceTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "bumpTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
], PBRMaterial2.prototype, "lightmapTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "refractionTexture", void 0);
__decorate([
BABYLON2.serializeAsColor3("ambient"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "ambientColor", void 0);
__decorate([
BABYLON2.serializeAsColor3("albedo"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "albedoColor", void 0);
__decorate([
BABYLON2.serializeAsColor3("reflectivity"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "reflectivityColor", void 0);
__decorate([
BABYLON2.serializeAsColor3("reflection"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "reflectionColor", void 0);
__decorate([
BABYLON2.serializeAsColor3("emissive"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "emissiveColor", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "microSurface", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "indexOfRefraction", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "invertRefractionY", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "linkRefractionWithTransparency", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useLightmapAsShadowmap", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial2.prototype, "useAlphaFromAlbedoTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial2.prototype, "forceAlphaTest", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial2.prototype, "alphaCutOff", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useSpecularOverAlpha", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useAmbientInGrayScale", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
__decorate([
BABYLON2.serialize()
], PBRMaterial2.prototype, "usePhysicalLightFalloff", null);
__decorate([
BABYLON2.serialize()
], PBRMaterial2.prototype, "useGLTFLightFalloff", null);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useRadianceOverAlpha", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useObjectSpaceNormalMap", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useParallax", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useParallaxOcclusion", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "parallaxScaleBias", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRMaterial2.prototype, "disableLighting", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "forceIrradianceInFragment", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], PBRMaterial2.prototype, "maxSimultaneousLights", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "invertNormalMapX", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "invertNormalMapY", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "twoSidedLighting", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useAlphaFresnel", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useLinearAlphaFresnel", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "environmentBRDFTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "forceNormalForward", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "enableSpecularAntiAliasing", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useHorizonOcclusion", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial2.prototype, "useRadianceOcclusion", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsMiscDirty")
], PBRMaterial2.prototype, "unlit", void 0);
return PBRMaterial2;
}(BABYLON2.PBRBaseMaterial)
);
BABYLON2.PBRMaterial = PBRMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PBRMetallicRoughnessMaterial = (
/** @class */
function(_super) {
__extends(PBRMetallicRoughnessMaterial2, _super);
function PBRMetallicRoughnessMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._useRoughnessFromMetallicTextureAlpha = false;
_this._useRoughnessFromMetallicTextureGreen = true;
_this._useMetallnessFromMetallicTextureBlue = true;
_this.metallic = 1;
_this.roughness = 1;
return _this;
}
PBRMetallicRoughnessMaterial2.prototype.getClassName = function() {
return "PBRMetallicRoughnessMaterial";
};
PBRMetallicRoughnessMaterial2.prototype.getActiveTextures = function() {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this.baseTexture) {
activeTextures.push(this.baseTexture);
}
if (this.metallicRoughnessTexture) {
activeTextures.push(this.metallicRoughnessTexture);
}
return activeTextures;
};
PBRMetallicRoughnessMaterial2.prototype.hasTexture = function(texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this.baseTexture === texture) {
return true;
}
if (this.metallicRoughnessTexture === texture) {
return true;
}
return false;
};
PBRMetallicRoughnessMaterial2.prototype.clone = function(name) {
var _this = this;
var clone = BABYLON2.SerializationHelper.Clone(function() {
return new PBRMetallicRoughnessMaterial2(name, _this.getScene());
}, this);
clone.id = name;
clone.name = name;
return clone;
};
PBRMetallicRoughnessMaterial2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
return serializationObject;
};
PBRMetallicRoughnessMaterial2.Parse = function(source, scene, rootUrl) {
return BABYLON2.SerializationHelper.Parse(function() {
return new PBRMetallicRoughnessMaterial2(source.name, scene);
}, source, scene, rootUrl);
};
__decorate([
BABYLON2.serializeAsColor3(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRMetallicRoughnessMaterial2.prototype, "baseColor", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRMetallicRoughnessMaterial2.prototype, "baseTexture", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial2.prototype, "metallic", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial2.prototype, "roughness", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
], PBRMetallicRoughnessMaterial2.prototype, "metallicRoughnessTexture", void 0);
return PBRMetallicRoughnessMaterial2;
}(BABYLON2.PBRBaseSimpleMaterial)
);
BABYLON2.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PBRSpecularGlossinessMaterial = (
/** @class */
function(_super) {
__extends(PBRSpecularGlossinessMaterial2, _super);
function PBRSpecularGlossinessMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._useMicroSurfaceFromReflectivityMapAlpha = true;
return _this;
}
PBRSpecularGlossinessMaterial2.prototype.getClassName = function() {
return "PBRSpecularGlossinessMaterial";
};
PBRSpecularGlossinessMaterial2.prototype.getActiveTextures = function() {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this.diffuseTexture) {
activeTextures.push(this.diffuseTexture);
}
if (this.specularGlossinessTexture) {
activeTextures.push(this.specularGlossinessTexture);
}
return activeTextures;
};
PBRSpecularGlossinessMaterial2.prototype.hasTexture = function(texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this.diffuseTexture === texture) {
return true;
}
if (this.specularGlossinessTexture === texture) {
return true;
}
return false;
};
PBRSpecularGlossinessMaterial2.prototype.clone = function(name) {
var _this = this;
var clone = BABYLON2.SerializationHelper.Clone(function() {
return new PBRSpecularGlossinessMaterial2(name, _this.getScene());
}, this);
clone.id = name;
clone.name = name;
return clone;
};
PBRSpecularGlossinessMaterial2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
return serializationObject;
};
PBRSpecularGlossinessMaterial2.Parse = function(source, scene, rootUrl) {
return BABYLON2.SerializationHelper.Parse(function() {
return new PBRSpecularGlossinessMaterial2(source.name, scene);
}, source, scene, rootUrl);
};
__decorate([
BABYLON2.serializeAsColor3("diffuse"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRSpecularGlossinessMaterial2.prototype, "diffuseColor", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRSpecularGlossinessMaterial2.prototype, "diffuseTexture", void 0);
__decorate([
BABYLON2.serializeAsColor3("specular"),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
], PBRSpecularGlossinessMaterial2.prototype, "specularColor", void 0);
__decorate([
BABYLON2.serialize(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
], PBRSpecularGlossinessMaterial2.prototype, "glossiness", void 0);
__decorate([
BABYLON2.serializeAsTexture(),
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
], PBRSpecularGlossinessMaterial2.prototype, "specularGlossinessTexture", void 0);
return PBRSpecularGlossinessMaterial2;
}(BABYLON2.PBRBaseSimpleMaterial)
);
BABYLON2.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.CameraInputTypes = {};
var CameraInputsManager = (
/** @class */
function() {
function CameraInputsManager2(camera2) {
this.attached = {};
this.camera = camera2;
this.checkInputs = function() {
};
}
CameraInputsManager2.prototype.add = function(input) {
var type = input.getSimpleName();
if (this.attached[type]) {
BABYLON2.Tools.Warn("camera input of type " + type + " already exists on camera");
return;
}
this.attached[type] = input;
input.camera = this.camera;
if (input.checkInputs) {
this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
}
if (this.attachedElement) {
input.attachControl(this.attachedElement);
}
};
CameraInputsManager2.prototype.remove = function(inputToRemove) {
for (var cam in this.attached) {
var input = this.attached[cam];
if (input === inputToRemove) {
input.detachControl(this.attachedElement);
input.camera = null;
delete this.attached[cam];
this.rebuildInputCheck();
}
}
};
CameraInputsManager2.prototype.removeByType = function(inputType) {
for (var cam in this.attached) {
var input = this.attached[cam];
if (input.getClassName() === inputType) {
input.detachControl(this.attachedElement);
input.camera = null;
delete this.attached[cam];
this.rebuildInputCheck();
}
}
};
CameraInputsManager2.prototype._addCheckInputs = function(fn) {
var current = this.checkInputs;
return function() {
current();
fn();
};
};
CameraInputsManager2.prototype.attachInput = function(input) {
if (this.attachedElement) {
input.attachControl(this.attachedElement, this.noPreventDefault);
}
};
CameraInputsManager2.prototype.attachElement = function(element, noPreventDefault) {
if (noPreventDefault === void 0) {
noPreventDefault = false;
}
if (this.attachedElement) {
return;
}
noPreventDefault = BABYLON2.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
this.attachedElement = element;
this.noPreventDefault = noPreventDefault;
for (var cam in this.attached) {
this.attached[cam].attachControl(element, noPreventDefault);
}
};
CameraInputsManager2.prototype.detachElement = function(element, disconnect) {
if (disconnect === void 0) {
disconnect = false;
}
if (this.attachedElement !== element) {
return;
}
for (var cam in this.attached) {
this.attached[cam].detachControl(element);
if (disconnect) {
this.attached[cam].camera = null;
}
}
this.attachedElement = null;
};
CameraInputsManager2.prototype.rebuildInputCheck = function() {
this.checkInputs = function() {
};
for (var cam in this.attached) {
var input = this.attached[cam];
if (input.checkInputs) {
this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
}
}
};
CameraInputsManager2.prototype.clear = function() {
if (this.attachedElement) {
this.detachElement(this.attachedElement, true);
}
this.attached = {};
this.attachedElement = null;
this.checkInputs = function() {
};
};
CameraInputsManager2.prototype.serialize = function(serializedCamera) {
var inputs = {};
for (var cam in this.attached) {
var input = this.attached[cam];
var res = BABYLON2.SerializationHelper.Serialize(input);
inputs[input.getClassName()] = res;
}
serializedCamera.inputsmgr = inputs;
};
CameraInputsManager2.prototype.parse = function(parsedCamera) {
var parsedInputs = parsedCamera.inputsmgr;
if (parsedInputs) {
this.clear();
for (var n in parsedInputs) {
var construct = BABYLON2.CameraInputTypes[n];
if (construct) {
var parsedinput = parsedInputs[n];
var input = BABYLON2.SerializationHelper.Parse(function() {
return new construct();
}, parsedinput, null);
this.add(input);
}
}
} else {
for (var n in this.attached) {
var construct = BABYLON2.CameraInputTypes[this.attached[n].getClassName()];
if (construct) {
var input = BABYLON2.SerializationHelper.Parse(function() {
return new construct();
}, parsedCamera, null);
this.remove(this.attached[n]);
this.add(input);
}
}
}
};
return CameraInputsManager2;
}()
);
BABYLON2.CameraInputsManager = CameraInputsManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var TargetCamera = (
/** @class */
function(_super) {
__extends(TargetCamera2, _super);
function TargetCamera2(name, position, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) {
setActiveOnSceneIfNoneActive = true;
}
var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
_this.cameraDirection = new BABYLON2.Vector3(0, 0, 0);
_this.cameraRotation = new BABYLON2.Vector2(0, 0);
_this.rotation = new BABYLON2.Vector3(0, 0, 0);
_this.speed = 2;
_this.noRotationConstraint = false;
_this.lockedTarget = null;
_this._currentTarget = BABYLON2.Vector3.Zero();
_this._viewMatrix = BABYLON2.Matrix.Zero();
_this._camMatrix = BABYLON2.Matrix.Zero();
_this._cameraTransformMatrix = BABYLON2.Matrix.Zero();
_this._cameraRotationMatrix = BABYLON2.Matrix.Zero();
_this._referencePoint = new BABYLON2.Vector3(0, 0, 1);
_this._transformedReferencePoint = BABYLON2.Vector3.Zero();
_this._globalCurrentTarget = BABYLON2.Vector3.Zero();
_this._globalCurrentUpVector = BABYLON2.Vector3.Zero();
_this._defaultUp = BABYLON2.Vector3.Up();
_this._cachedRotationZ = 0;
_this._cachedQuaternionRotationZ = 0;
return _this;
}
TargetCamera2.prototype.getFrontPosition = function(distance) {
this.getWorldMatrix();
var direction = this.getTarget().subtract(this.position);
direction.normalize();
direction.scaleInPlace(distance);
return this.globalPosition.add(direction);
};
TargetCamera2.prototype._getLockedTargetPosition = function() {
if (!this.lockedTarget) {
return null;
}
if (this.lockedTarget.absolutePosition) {
this.lockedTarget.computeWorldMatrix();
}
return this.lockedTarget.absolutePosition || this.lockedTarget;
};
TargetCamera2.prototype.storeState = function() {
this._storedPosition = this.position.clone();
this._storedRotation = this.rotation.clone();
if (this.rotationQuaternion) {
this._storedRotationQuaternion = this.rotationQuaternion.clone();
}
return _super.prototype.storeState.call(this);
};
TargetCamera2.prototype._restoreStateValues = function() {
if (!_super.prototype._restoreStateValues.call(this)) {
return false;
}
this.position = this._storedPosition.clone();
this.rotation = this._storedRotation.clone();
if (this.rotationQuaternion) {
this.rotationQuaternion = this._storedRotationQuaternion.clone();
}
this.cameraDirection.copyFromFloats(0, 0, 0);
this.cameraRotation.copyFromFloats(0, 0);
return true;
};
TargetCamera2.prototype._initCache = function() {
_super.prototype._initCache.call(this);
this._cache.lockedTarget = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.rotation = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.rotationQuaternion = new BABYLON2.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
};
TargetCamera2.prototype._updateCache = function(ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
var lockedTargetPosition = this._getLockedTargetPosition();
if (!lockedTargetPosition) {
this._cache.lockedTarget = null;
} else {
if (!this._cache.lockedTarget) {
this._cache.lockedTarget = lockedTargetPosition.clone();
} else {
this._cache.lockedTarget.copyFrom(lockedTargetPosition);
}
}
this._cache.rotation.copyFrom(this.rotation);
if (this.rotationQuaternion) {
this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
}
};
TargetCamera2.prototype._isSynchronizedViewMatrix = function() {
if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
return false;
}
var lockedTargetPosition = this._getLockedTargetPosition();
return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
};
TargetCamera2.prototype._computeLocalCameraSpeed = function() {
var engine = this.getEngine();
return this.speed * Math.sqrt(engine.getDeltaTime() / (engine.getFps() * 100));
};
TargetCamera2.prototype.setTarget = function(target) {
this.upVector.normalize();
if (this.position.z === target.z) {
this.position.z += BABYLON2.Epsilon;
}
BABYLON2.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
this._camMatrix.invert();
this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
var vDir = target.subtract(this.position);
if (vDir.x >= 0) {
this.rotation.y = -Math.atan(vDir.z / vDir.x) + Math.PI / 2;
} else {
this.rotation.y = -Math.atan(vDir.z / vDir.x) - Math.PI / 2;
}
this.rotation.z = 0;
if (isNaN(this.rotation.x)) {
this.rotation.x = 0;
}
if (isNaN(this.rotation.y)) {
this.rotation.y = 0;
}
if (isNaN(this.rotation.z)) {
this.rotation.z = 0;
}
if (this.rotationQuaternion) {
BABYLON2.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
}
};
TargetCamera2.prototype.getTarget = function() {
return this._currentTarget;
};
TargetCamera2.prototype._decideIfNeedsToMove = function() {
return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
};
TargetCamera2.prototype._updatePosition = function() {
if (this.parent) {
this.parent.getWorldMatrix().invertToRef(BABYLON2.Tmp.Matrix[0]);
BABYLON2.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON2.Tmp.Matrix[0], BABYLON2.Tmp.Vector3[0]);
this.position.addInPlace(BABYLON2.Tmp.Vector3[0]);
return;
}
this.position.addInPlace(this.cameraDirection);
};
TargetCamera2.prototype._checkInputs = function() {
var needToMove = this._decideIfNeedsToMove();
var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
if (needToMove) {
this._updatePosition();
}
if (needToRotate) {
this.rotation.x += this.cameraRotation.x;
this.rotation.y += this.cameraRotation.y;
if (this.rotationQuaternion) {
var len = this.rotation.lengthSquared();
if (len) {
BABYLON2.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
}
}
if (!this.noRotationConstraint) {
var limit = Math.PI / 2 * 0.95;
if (this.rotation.x > limit) {
this.rotation.x = limit;
}
if (this.rotation.x < -limit) {
this.rotation.x = -limit;
}
}
}
if (needToMove) {
if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON2.Epsilon) {
this.cameraDirection.x = 0;
}
if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON2.Epsilon) {
this.cameraDirection.y = 0;
}
if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON2.Epsilon) {
this.cameraDirection.z = 0;
}
this.cameraDirection.scaleInPlace(this.inertia);
}
if (needToRotate) {
if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON2.Epsilon) {
this.cameraRotation.x = 0;
}
if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON2.Epsilon) {
this.cameraRotation.y = 0;
}
this.cameraRotation.scaleInPlace(this.inertia);
}
_super.prototype._checkInputs.call(this);
};
TargetCamera2.prototype._updateCameraRotationMatrix = function() {
if (this.rotationQuaternion) {
this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
} else {
BABYLON2.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
}
};
TargetCamera2.prototype._rotateUpVectorWithCameraRotationMatrix = function() {
BABYLON2.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
return this;
};
TargetCamera2.prototype._getViewMatrix = function() {
if (this.lockedTarget) {
this.setTarget(this._getLockedTargetPosition());
}
this._updateCameraRotationMatrix();
if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
this._rotateUpVectorWithCameraRotationMatrix();
this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
} else if (this._cachedRotationZ != this.rotation.z) {
this._rotateUpVectorWithCameraRotationMatrix();
this._cachedRotationZ = this.rotation.z;
}
BABYLON2.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
return this._viewMatrix;
};
TargetCamera2.prototype._computeViewMatrix = function(position, target, up) {
if (this.parent) {
var parentWorldMatrix = this.parent.getWorldMatrix();
BABYLON2.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
BABYLON2.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
BABYLON2.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
this._markSyncedWithParent();
} else {
this._globalPosition.copyFrom(position);
this._globalCurrentTarget.copyFrom(target);
this._globalCurrentUpVector.copyFrom(up);
}
if (this.getScene().useRightHandedSystem) {
BABYLON2.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
} else {
BABYLON2.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
}
};
TargetCamera2.prototype.createRigCamera = function(name, cameraIndex) {
if (this.cameraRigMode !== BABYLON2.Camera.RIG_MODE_NONE) {
var rigCamera = new TargetCamera2(name, this.position.clone(), this.getScene());
if (this.cameraRigMode === BABYLON2.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON2.Camera.RIG_MODE_WEBVR) {
if (!this.rotationQuaternion) {
this.rotationQuaternion = new BABYLON2.Quaternion();
}
rigCamera._cameraRigParams = {};
rigCamera.rotationQuaternion = new BABYLON2.Quaternion();
}
return rigCamera;
}
return null;
};
TargetCamera2.prototype._updateRigCameras = function() {
var camLeft = this._rigCameras[0];
var camRight = this._rigCameras[1];
switch (this.cameraRigMode) {
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
var leftSign = this.cameraRigMode === BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? 1 : -1;
var rightSign = this.cameraRigMode === BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED ? -1 : 1;
this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
camLeft.setTarget(this.getTarget());
camRight.setTarget(this.getTarget());
break;
case BABYLON2.Camera.RIG_MODE_VR:
if (camLeft.rotationQuaternion) {
camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
} else {
camLeft.rotation.copyFrom(this.rotation);
camRight.rotation.copyFrom(this.rotation);
}
camLeft.position.copyFrom(this.position);
camRight.position.copyFrom(this.position);
break;
}
_super.prototype._updateRigCameras.call(this);
};
TargetCamera2.prototype._getRigCamPosition = function(halfSpace, result) {
if (!this._rigCamTransformMatrix) {
this._rigCamTransformMatrix = new BABYLON2.Matrix();
}
var target = this.getTarget();
BABYLON2.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON2.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON2.Matrix.Translation(target.x, target.y, target.z));
BABYLON2.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
};
TargetCamera2.prototype.getClassName = function() {
return "TargetCamera";
};
__decorate([
BABYLON2.serializeAsVector3()
], TargetCamera2.prototype, "rotation", void 0);
__decorate([
BABYLON2.serialize()
], TargetCamera2.prototype, "speed", void 0);
__decorate([
BABYLON2.serializeAsMeshReference("lockedTargetId")
], TargetCamera2.prototype, "lockedTarget", void 0);
return TargetCamera2;
}(BABYLON2.Camera)
);
BABYLON2.TargetCamera = TargetCamera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FreeCameraMouseInput = (
/** @class */
function() {
function FreeCameraMouseInput2(touchEnabled) {
if (touchEnabled === void 0) {
touchEnabled = true;
}
this.touchEnabled = touchEnabled;
this.buttons = [0, 1, 2];
this.angularSensibility = 2e3;
this.previousPosition = null;
}
FreeCameraMouseInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
var engine = this.camera.getEngine();
if (!this._pointerInput) {
this._pointerInput = function(p, s) {
var evt = p.event;
if (engine.isInVRExclusivePointerMode) {
return;
}
if (!_this.touchEnabled && evt.pointerType === "touch") {
return;
}
if (p.type !== BABYLON2.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
return;
}
var srcElement = evt.srcElement || evt.target;
if (p.type === BABYLON2.PointerEventTypes.POINTERDOWN && srcElement) {
try {
srcElement.setPointerCapture(evt.pointerId);
} catch (e2) {
}
_this.previousPosition = {
x: evt.clientX,
y: evt.clientY
};
if (!noPreventDefault) {
evt.preventDefault();
element.focus();
}
} else if (p.type === BABYLON2.PointerEventTypes.POINTERUP && srcElement) {
try {
srcElement.releasePointerCapture(evt.pointerId);
} catch (e2) {
}
_this.previousPosition = null;
if (!noPreventDefault) {
evt.preventDefault();
}
} else if (p.type === BABYLON2.PointerEventTypes.POINTERMOVE) {
if (!_this.previousPosition || engine.isPointerLock) {
return;
}
var offsetX = evt.clientX - _this.previousPosition.x;
if (_this.camera.getScene().useRightHandedSystem) {
offsetX *= -1;
}
if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
offsetX *= -1;
}
_this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
var offsetY = evt.clientY - _this.previousPosition.y;
_this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
_this.previousPosition = {
x: evt.clientX,
y: evt.clientY
};
if (!noPreventDefault) {
evt.preventDefault();
}
}
};
}
this._onMouseMove = function(evt) {
if (!engine.isPointerLock) {
return;
}
if (engine.isInVRExclusivePointerMode) {
return;
}
var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
if (_this.camera.getScene().useRightHandedSystem) {
offsetX *= -1;
}
if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
offsetX *= -1;
}
_this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
_this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
_this.previousPosition = null;
if (!noPreventDefault) {
evt.preventDefault();
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON2.PointerEventTypes.POINTERDOWN | BABYLON2.PointerEventTypes.POINTERUP | BABYLON2.PointerEventTypes.POINTERMOVE);
element.addEventListener("mousemove", this._onMouseMove, false);
};
FreeCameraMouseInput2.prototype.detachControl = function(element) {
if (this._observer && element) {
this.camera.getScene().onPointerObservable.remove(this._observer);
if (this._onMouseMove) {
element.removeEventListener("mousemove", this._onMouseMove);
}
this._observer = null;
this._onMouseMove = null;
this.previousPosition = null;
}
};
FreeCameraMouseInput2.prototype.getClassName = function() {
return "FreeCameraMouseInput";
};
FreeCameraMouseInput2.prototype.getSimpleName = function() {
return "mouse";
};
__decorate([
BABYLON2.serialize()
], FreeCameraMouseInput2.prototype, "buttons", void 0);
__decorate([
BABYLON2.serialize()
], FreeCameraMouseInput2.prototype, "angularSensibility", void 0);
return FreeCameraMouseInput2;
}()
);
BABYLON2.FreeCameraMouseInput = FreeCameraMouseInput;
BABYLON2.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FreeCameraKeyboardMoveInput = (
/** @class */
function() {
function FreeCameraKeyboardMoveInput2() {
this.keysUp = [38];
this.keysDown = [40];
this.keysLeft = [37];
this.keysRight = [39];
this._keys = new Array();
}
FreeCameraKeyboardMoveInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
if (this._onCanvasBlurObserver) {
return;
}
this._scene = this.camera.getScene();
this._engine = this._scene.getEngine();
this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function() {
_this._keys = [];
});
this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function(info) {
var evt = info.event;
if (info.type === BABYLON2.KeyboardEventTypes.KEYDOWN) {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index === -1) {
_this._keys.push(evt.keyCode);
}
if (!noPreventDefault) {
evt.preventDefault();
}
}
} else {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index >= 0) {
_this._keys.splice(index, 1);
}
if (!noPreventDefault) {
evt.preventDefault();
}
}
}
});
};
FreeCameraKeyboardMoveInput2.prototype.detachControl = function(element) {
if (this._scene) {
if (this._onKeyboardObserver) {
this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
}
if (this._onCanvasBlurObserver) {
this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
}
this._onKeyboardObserver = null;
this._onCanvasBlurObserver = null;
}
this._keys = [];
};
FreeCameraKeyboardMoveInput2.prototype.checkInputs = function() {
if (this._onKeyboardObserver) {
var camera2 = this.camera;
for (var index = 0; index < this._keys.length; index++) {
var keyCode = this._keys[index];
var speed = camera2._computeLocalCameraSpeed();
if (this.keysLeft.indexOf(keyCode) !== -1) {
camera2._localDirection.copyFromFloats(-speed, 0, 0);
} else if (this.keysUp.indexOf(keyCode) !== -1) {
camera2._localDirection.copyFromFloats(0, 0, speed);
} else if (this.keysRight.indexOf(keyCode) !== -1) {
camera2._localDirection.copyFromFloats(speed, 0, 0);
} else if (this.keysDown.indexOf(keyCode) !== -1) {
camera2._localDirection.copyFromFloats(0, 0, -speed);
}
if (camera2.getScene().useRightHandedSystem) {
camera2._localDirection.z *= -1;
}
camera2.getViewMatrix().invertToRef(camera2._cameraTransformMatrix);
BABYLON2.Vector3.TransformNormalToRef(camera2._localDirection, camera2._cameraTransformMatrix, camera2._transformedDirection);
camera2.cameraDirection.addInPlace(camera2._transformedDirection);
}
}
};
FreeCameraKeyboardMoveInput2.prototype.getClassName = function() {
return "FreeCameraKeyboardMoveInput";
};
FreeCameraKeyboardMoveInput2.prototype._onLostFocus = function(e2) {
this._keys = [];
};
FreeCameraKeyboardMoveInput2.prototype.getSimpleName = function() {
return "keyboard";
};
__decorate([
BABYLON2.serialize()
], FreeCameraKeyboardMoveInput2.prototype, "keysUp", void 0);
__decorate([
BABYLON2.serialize()
], FreeCameraKeyboardMoveInput2.prototype, "keysDown", void 0);
__decorate([
BABYLON2.serialize()
], FreeCameraKeyboardMoveInput2.prototype, "keysLeft", void 0);
__decorate([
BABYLON2.serialize()
], FreeCameraKeyboardMoveInput2.prototype, "keysRight", void 0);
return FreeCameraKeyboardMoveInput2;
}()
);
BABYLON2.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
BABYLON2.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FreeCameraInputsManager = (
/** @class */
function(_super) {
__extends(FreeCameraInputsManager2, _super);
function FreeCameraInputsManager2(camera2) {
return _super.call(this, camera2) || this;
}
FreeCameraInputsManager2.prototype.addKeyboard = function() {
this.add(new BABYLON2.FreeCameraKeyboardMoveInput());
return this;
};
FreeCameraInputsManager2.prototype.addMouse = function(touchEnabled) {
if (touchEnabled === void 0) {
touchEnabled = true;
}
this.add(new BABYLON2.FreeCameraMouseInput(touchEnabled));
return this;
};
FreeCameraInputsManager2.prototype.addDeviceOrientation = function() {
this.add(new BABYLON2.FreeCameraDeviceOrientationInput());
return this;
};
FreeCameraInputsManager2.prototype.addTouch = function() {
this.add(new BABYLON2.FreeCameraTouchInput());
return this;
};
FreeCameraInputsManager2.prototype.addVirtualJoystick = function() {
this.add(new BABYLON2.FreeCameraVirtualJoystickInput());
return this;
};
return FreeCameraInputsManager2;
}(BABYLON2.CameraInputsManager)
);
BABYLON2.FreeCameraInputsManager = FreeCameraInputsManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("FreeCamera", function(name, scene) {
return function() {
return new BABYLON2.UniversalCamera(name, BABYLON2.Vector3.Zero(), scene);
};
});
var FreeCamera = (
/** @class */
function(_super) {
__extends(FreeCamera2, _super);
function FreeCamera2(name, position, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) {
setActiveOnSceneIfNoneActive = true;
}
var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
_this.ellipsoid = new BABYLON2.Vector3(0.5, 1, 0.5);
_this.ellipsoidOffset = new BABYLON2.Vector3(0, 0, 0);
_this.checkCollisions = false;
_this.applyGravity = false;
_this._needMoveForGravity = false;
_this._oldPosition = BABYLON2.Vector3.Zero();
_this._diffPosition = BABYLON2.Vector3.Zero();
_this._newPosition = BABYLON2.Vector3.Zero();
_this._collisionMask = -1;
_this._onCollisionPositionChange = function(collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) {
collidedMesh = null;
}
if (_this.getScene().workerCollisions) {
newPosition.multiplyInPlace(_this._collider._radius);
}
var updatePosition = function(newPos) {
_this._newPosition.copyFrom(newPos);
_this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
if (_this._diffPosition.length() > BABYLON2.Engine.CollisionsEpsilon) {
_this.position.addInPlace(_this._diffPosition);
if (_this.onCollide && collidedMesh) {
_this.onCollide(collidedMesh);
}
}
};
updatePosition(newPosition);
};
_this.inputs = new BABYLON2.FreeCameraInputsManager(_this);
_this.inputs.addKeyboard().addMouse();
return _this;
}
Object.defineProperty(FreeCamera2.prototype, "angularSensibility", {
/**
* Gets the input sensibility for a mouse input. (default is 2000.0)
* Higher values reduce sensitivity.
*/
get: function() {
var mouse = this.inputs.attached["mouse"];
if (mouse) {
return mouse.angularSensibility;
}
return 0;
},
/**
* Sets the input sensibility for a mouse input. (default is 2000.0)
* Higher values reduce sensitivity.
*/
set: function(value) {
var mouse = this.inputs.attached["mouse"];
if (mouse) {
mouse.angularSensibility = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera2.prototype, "keysUp", {
/**
* Gets or Set the list of keyboard keys used to control the forward move of the camera.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysUp;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysUp = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera2.prototype, "keysDown", {
/**
* Gets or Set the list of keyboard keys used to control the backward move of the camera.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysDown;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysDown = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera2.prototype, "keysLeft", {
/**
* Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysLeft;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysLeft = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(FreeCamera2.prototype, "keysRight", {
/**
* Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysRight;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysRight = value;
}
},
enumerable: true,
configurable: true
});
FreeCamera2.prototype.attachControl = function(element, noPreventDefault) {
this.inputs.attachElement(element, noPreventDefault);
};
FreeCamera2.prototype.detachControl = function(element) {
this.inputs.detachElement(element);
this.cameraDirection = new BABYLON2.Vector3(0, 0, 0);
this.cameraRotation = new BABYLON2.Vector2(0, 0);
};
Object.defineProperty(FreeCamera2.prototype, "collisionMask", {
/**
* Define a collision mask to limit the list of object the camera can collide with
*/
get: function() {
return this._collisionMask;
},
set: function(mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: true,
configurable: true
});
FreeCamera2.prototype._collideWithWorld = function(displacement) {
var globalPosition;
if (this.parent) {
globalPosition = BABYLON2.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
} else {
globalPosition = this.position;
}
globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
this._oldPosition.addInPlace(this.ellipsoidOffset);
if (!this._collider) {
this._collider = new BABYLON2.Collider();
}
this._collider._radius = this.ellipsoid;
this._collider.collisionMask = this._collisionMask;
var actualDisplacement = displacement;
if (this.applyGravity) {
actualDisplacement = displacement.add(this.getScene().gravity);
}
this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
};
FreeCamera2.prototype._checkInputs = function() {
if (!this._localDirection) {
this._localDirection = BABYLON2.Vector3.Zero();
this._transformedDirection = BABYLON2.Vector3.Zero();
}
this.inputs.checkInputs();
_super.prototype._checkInputs.call(this);
};
FreeCamera2.prototype._decideIfNeedsToMove = function() {
return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
};
FreeCamera2.prototype._updatePosition = function() {
if (this.checkCollisions && this.getScene().collisionsEnabled) {
this._collideWithWorld(this.cameraDirection);
} else {
_super.prototype._updatePosition.call(this);
}
};
FreeCamera2.prototype.dispose = function() {
this.inputs.clear();
_super.prototype.dispose.call(this);
};
FreeCamera2.prototype.getClassName = function() {
return "FreeCamera";
};
__decorate([
BABYLON2.serializeAsVector3()
], FreeCamera2.prototype, "ellipsoid", void 0);
__decorate([
BABYLON2.serializeAsVector3()
], FreeCamera2.prototype, "ellipsoidOffset", void 0);
__decorate([
BABYLON2.serialize()
], FreeCamera2.prototype, "checkCollisions", void 0);
__decorate([
BABYLON2.serialize()
], FreeCamera2.prototype, "applyGravity", void 0);
return FreeCamera2;
}(BABYLON2.TargetCamera)
);
BABYLON2.FreeCamera = FreeCamera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ArcRotateCameraKeyboardMoveInput = (
/** @class */
function() {
function ArcRotateCameraKeyboardMoveInput2() {
this.keysUp = [38];
this.keysDown = [40];
this.keysLeft = [37];
this.keysRight = [39];
this.keysReset = [220];
this.panningSensibility = 50;
this.zoomingSensibility = 25;
this.useAltToZoom = true;
this.angularSpeed = 0.01;
this._keys = new Array();
}
ArcRotateCameraKeyboardMoveInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
if (this._onCanvasBlurObserver) {
return;
}
this._scene = this.camera.getScene();
this._engine = this._scene.getEngine();
this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function() {
_this._keys = [];
});
this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function(info) {
var evt = info.event;
if (info.type === BABYLON2.KeyboardEventTypes.KEYDOWN) {
_this._ctrlPressed = evt.ctrlKey;
_this._altPressed = evt.altKey;
if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysReset.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index === -1) {
_this._keys.push(evt.keyCode);
}
if (evt.preventDefault) {
if (!noPreventDefault) {
evt.preventDefault();
}
}
}
} else {
if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysReset.indexOf(evt.keyCode) !== -1) {
var index = _this._keys.indexOf(evt.keyCode);
if (index >= 0) {
_this._keys.splice(index, 1);
}
if (evt.preventDefault) {
if (!noPreventDefault) {
evt.preventDefault();
}
}
}
}
});
};
ArcRotateCameraKeyboardMoveInput2.prototype.detachControl = function(element) {
if (this._scene) {
if (this._onKeyboardObserver) {
this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
}
if (this._onCanvasBlurObserver) {
this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
}
this._onKeyboardObserver = null;
this._onCanvasBlurObserver = null;
}
this._keys = [];
};
ArcRotateCameraKeyboardMoveInput2.prototype.checkInputs = function() {
if (this._onKeyboardObserver) {
var camera2 = this.camera;
for (var index = 0; index < this._keys.length; index++) {
var keyCode = this._keys[index];
if (this.keysLeft.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera2.inertialPanningX -= 1 / this.panningSensibility;
} else {
camera2.inertialAlphaOffset -= this.angularSpeed;
}
} else if (this.keysUp.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera2.inertialPanningY += 1 / this.panningSensibility;
} else if (this._altPressed && this.useAltToZoom) {
camera2.inertialRadiusOffset += 1 / this.zoomingSensibility;
} else {
camera2.inertialBetaOffset -= this.angularSpeed;
}
} else if (this.keysRight.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera2.inertialPanningX += 1 / this.panningSensibility;
} else {
camera2.inertialAlphaOffset += this.angularSpeed;
}
} else if (this.keysDown.indexOf(keyCode) !== -1) {
if (this._ctrlPressed && this.camera._useCtrlForPanning) {
camera2.inertialPanningY -= 1 / this.panningSensibility;
} else if (this._altPressed && this.useAltToZoom) {
camera2.inertialRadiusOffset -= 1 / this.zoomingSensibility;
} else {
camera2.inertialBetaOffset += this.angularSpeed;
}
} else if (this.keysReset.indexOf(keyCode) !== -1) {
if (camera2.useInputToRestoreState) {
camera2.restoreState();
}
}
}
}
};
ArcRotateCameraKeyboardMoveInput2.prototype.getClassName = function() {
return "ArcRotateCameraKeyboardMoveInput";
};
ArcRotateCameraKeyboardMoveInput2.prototype.getSimpleName = function() {
return "keyboard";
};
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "keysUp", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "keysDown", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "keysLeft", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "keysRight", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "keysReset", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "panningSensibility", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "zoomingSensibility", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "useAltToZoom", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraKeyboardMoveInput2.prototype, "angularSpeed", void 0);
return ArcRotateCameraKeyboardMoveInput2;
}()
);
BABYLON2.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
BABYLON2.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ArcRotateCameraMouseWheelInput = (
/** @class */
function() {
function ArcRotateCameraMouseWheelInput2() {
this.wheelPrecision = 3;
this.wheelDeltaPercentage = 0;
}
ArcRotateCameraMouseWheelInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
this._wheel = function(p, s) {
if (p.type !== BABYLON2.PointerEventTypes.POINTERWHEEL) {
return;
}
var event = p.event;
var delta = 0;
if (event.wheelDelta) {
if (_this.wheelDeltaPercentage) {
var wheelDelta = event.wheelDelta * 0.01 * _this.wheelDeltaPercentage * _this.camera.radius;
if (event.wheelDelta > 0) {
delta = wheelDelta / (1 + _this.wheelDeltaPercentage);
} else {
delta = wheelDelta * (1 + _this.wheelDeltaPercentage);
}
} else {
delta = event.wheelDelta / (_this.wheelPrecision * 40);
}
} else if (event.detail) {
delta = -event.detail / _this.wheelPrecision;
}
if (delta) {
_this.camera.inertialRadiusOffset += delta;
}
if (event.preventDefault) {
if (!noPreventDefault) {
event.preventDefault();
}
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON2.PointerEventTypes.POINTERWHEEL);
};
ArcRotateCameraMouseWheelInput2.prototype.detachControl = function(element) {
if (this._observer && element) {
this.camera.getScene().onPointerObservable.remove(this._observer);
this._observer = null;
this._wheel = null;
}
};
ArcRotateCameraMouseWheelInput2.prototype.getClassName = function() {
return "ArcRotateCameraMouseWheelInput";
};
ArcRotateCameraMouseWheelInput2.prototype.getSimpleName = function() {
return "mousewheel";
};
__decorate([
BABYLON2.serialize()
], ArcRotateCameraMouseWheelInput2.prototype, "wheelPrecision", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraMouseWheelInput2.prototype, "wheelDeltaPercentage", void 0);
return ArcRotateCameraMouseWheelInput2;
}()
);
BABYLON2.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
BABYLON2.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ArcRotateCameraPointersInput = (
/** @class */
function() {
function ArcRotateCameraPointersInput2() {
this.buttons = [0, 1, 2];
this.angularSensibilityX = 1e3;
this.angularSensibilityY = 1e3;
this.pinchPrecision = 12;
this.pinchDeltaPercentage = 0;
this.panningSensibility = 1e3;
this.multiTouchPanning = true;
this.multiTouchPanAndZoom = true;
this.pinchInwards = true;
this._isPanClick = false;
}
ArcRotateCameraPointersInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
var engine = this.camera.getEngine();
var cacheSoloPointer;
var pointA = null;
var pointB = null;
var previousPinchSquaredDistance = 0;
var initialDistance = 0;
var twoFingerActivityCount = 0;
var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
this._pointerInput = function(p, s) {
var evt = p.event;
var isTouch = p.event.pointerType === "touch";
if (engine.isInVRExclusivePointerMode) {
return;
}
if (p.type !== BABYLON2.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
return;
}
var srcElement = evt.srcElement || evt.target;
if (p.type === BABYLON2.PointerEventTypes.POINTERDOWN && srcElement) {
try {
srcElement.setPointerCapture(evt.pointerId);
} catch (e2) {
}
_this._isPanClick = evt.button === _this.camera._panningMouseButton;
cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
if (pointA === null) {
pointA = cacheSoloPointer;
} else if (pointB === null) {
pointB = cacheSoloPointer;
}
if (!noPreventDefault) {
evt.preventDefault();
element.focus();
}
} else if (p.type === BABYLON2.PointerEventTypes.POINTERDOUBLETAP) {
if (_this.camera.useInputToRestoreState) {
_this.camera.restoreState();
}
} else if (p.type === BABYLON2.PointerEventTypes.POINTERUP && srcElement) {
try {
srcElement.releasePointerCapture(evt.pointerId);
} catch (e2) {
}
cacheSoloPointer = null;
previousPinchSquaredDistance = 0;
previousMultiTouchPanPosition.isPaning = false;
previousMultiTouchPanPosition.isPinching = false;
twoFingerActivityCount = 0;
initialDistance = 0;
if (!isTouch) {
pointB = null;
}
if (engine._badOS) {
pointA = pointB = null;
} else {
if (pointB && pointA && pointA.pointerId == evt.pointerId) {
pointA = pointB;
pointB = null;
cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
} else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
pointB = null;
cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
} else {
pointA = pointB = null;
}
}
if (!noPreventDefault) {
evt.preventDefault();
}
} else if (p.type === BABYLON2.PointerEventTypes.POINTERMOVE) {
if (!noPreventDefault) {
evt.preventDefault();
}
if (pointA && pointB === null && cacheSoloPointer) {
if (_this.panningSensibility !== 0 && (evt.ctrlKey && _this.camera._useCtrlForPanning || _this._isPanClick)) {
_this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
_this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
} else {
var offsetX = evt.clientX - cacheSoloPointer.x;
var offsetY = evt.clientY - cacheSoloPointer.y;
_this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
_this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
}
cacheSoloPointer.x = evt.clientX;
cacheSoloPointer.y = evt.clientY;
} else if (pointA && pointB) {
var ed = pointA.pointerId === evt.pointerId ? pointA : pointB;
ed.x = evt.clientX;
ed.y = evt.clientY;
var direction = _this.pinchInwards ? 1 : -1;
var distX = pointA.x - pointB.x;
var distY = pointA.y - pointB.y;
var pinchSquaredDistance = distX * distX + distY * distY;
var pinchDistance = Math.sqrt(pinchSquaredDistance);
if (previousPinchSquaredDistance === 0) {
initialDistance = pinchDistance;
previousPinchSquaredDistance = pinchSquaredDistance;
previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
return;
}
if (_this.multiTouchPanAndZoom) {
if (_this.pinchDeltaPercentage) {
_this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 1e-3 * _this.camera.radius * _this.pinchDeltaPercentage;
} else {
_this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
}
if (_this.panningSensibility !== 0) {
var pointersCenterX = (pointA.x + pointB.x) / 2;
var pointersCenterY = (pointA.y + pointB.y) / 2;
var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
previousMultiTouchPanPosition.x = pointersCenterX;
previousMultiTouchPanPosition.y = pointersCenterY;
_this.camera.inertialPanningX += -pointersCenterDistX / _this.panningSensibility;
_this.camera.inertialPanningY += pointersCenterDistY / _this.panningSensibility;
}
} else {
twoFingerActivityCount++;
if (previousMultiTouchPanPosition.isPinching || twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance) {
if (_this.pinchDeltaPercentage) {
_this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 1e-3 * _this.camera.radius * _this.pinchDeltaPercentage;
} else {
_this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
}
previousMultiTouchPanPosition.isPaning = false;
previousMultiTouchPanPosition.isPinching = true;
} else {
if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
if (!previousMultiTouchPanPosition.isPaning) {
previousMultiTouchPanPosition.isPaning = true;
previousMultiTouchPanPosition.isPinching = false;
previousMultiTouchPanPosition.x = ed.x;
previousMultiTouchPanPosition.y = ed.y;
return;
}
_this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / _this.panningSensibility;
_this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / _this.panningSensibility;
}
}
if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
previousMultiTouchPanPosition.x = ed.x;
previousMultiTouchPanPosition.y = ed.y;
}
}
previousPinchSquaredDistance = pinchSquaredDistance;
}
}
};
this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON2.PointerEventTypes.POINTERDOWN | BABYLON2.PointerEventTypes.POINTERUP | BABYLON2.PointerEventTypes.POINTERMOVE | BABYLON2.PointerEventTypes.POINTERDOUBLETAP);
this._onContextMenu = function(evt) {
evt.preventDefault();
};
if (!this.camera._useCtrlForPanning) {
element.addEventListener("contextmenu", this._onContextMenu, false);
}
this._onLostFocus = function() {
pointA = pointB = null;
previousPinchSquaredDistance = 0;
previousMultiTouchPanPosition.isPaning = false;
previousMultiTouchPanPosition.isPinching = false;
twoFingerActivityCount = 0;
cacheSoloPointer = null;
initialDistance = 0;
};
this._onMouseMove = function(evt) {
if (!engine.isPointerLock) {
return;
}
var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
_this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
_this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
if (!noPreventDefault) {
evt.preventDefault();
}
};
this._onGestureStart = function(e2) {
if (window.MSGesture === void 0) {
return;
}
if (!_this._MSGestureHandler) {
_this._MSGestureHandler = new MSGesture();
_this._MSGestureHandler.target = element;
}
_this._MSGestureHandler.addPointer(e2.pointerId);
};
this._onGesture = function(e2) {
_this.camera.radius *= e2.scale;
if (e2.preventDefault) {
if (!noPreventDefault) {
e2.stopPropagation();
e2.preventDefault();
}
}
};
element.addEventListener("mousemove", this._onMouseMove, false);
element.addEventListener("MSPointerDown", this._onGestureStart, false);
element.addEventListener("MSGestureChange", this._onGesture, false);
BABYLON2.Tools.RegisterTopRootEvents([
{ name: "blur", handler: this._onLostFocus }
]);
};
ArcRotateCameraPointersInput2.prototype.detachControl = function(element) {
if (this._onLostFocus) {
BABYLON2.Tools.UnregisterTopRootEvents([
{ name: "blur", handler: this._onLostFocus }
]);
}
if (element && this._observer) {
this.camera.getScene().onPointerObservable.remove(this._observer);
this._observer = null;
if (this._onContextMenu) {
element.removeEventListener("contextmenu", this._onContextMenu);
}
if (this._onMouseMove) {
element.removeEventListener("mousemove", this._onMouseMove);
}
if (this._onGestureStart) {
element.removeEventListener("MSPointerDown", this._onGestureStart);
}
if (this._onGesture) {
element.removeEventListener("MSGestureChange", this._onGesture);
}
this._isPanClick = false;
this.pinchInwards = true;
this._onMouseMove = null;
this._onGestureStart = null;
this._onGesture = null;
this._MSGestureHandler = null;
this._onLostFocus = null;
this._onContextMenu = null;
}
};
ArcRotateCameraPointersInput2.prototype.getClassName = function() {
return "ArcRotateCameraPointersInput";
};
ArcRotateCameraPointersInput2.prototype.getSimpleName = function() {
return "pointers";
};
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "buttons", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "angularSensibilityX", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "angularSensibilityY", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "pinchPrecision", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "pinchDeltaPercentage", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "panningSensibility", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "multiTouchPanning", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraPointersInput2.prototype, "multiTouchPanAndZoom", void 0);
return ArcRotateCameraPointersInput2;
}()
);
BABYLON2.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
BABYLON2.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ArcRotateCameraInputsManager = (
/** @class */
function(_super) {
__extends(ArcRotateCameraInputsManager2, _super);
function ArcRotateCameraInputsManager2(camera2) {
return _super.call(this, camera2) || this;
}
ArcRotateCameraInputsManager2.prototype.addMouseWheel = function() {
this.add(new BABYLON2.ArcRotateCameraMouseWheelInput());
return this;
};
ArcRotateCameraInputsManager2.prototype.addPointers = function() {
this.add(new BABYLON2.ArcRotateCameraPointersInput());
return this;
};
ArcRotateCameraInputsManager2.prototype.addKeyboard = function() {
this.add(new BABYLON2.ArcRotateCameraKeyboardMoveInput());
return this;
};
ArcRotateCameraInputsManager2.prototype.addVRDeviceOrientation = function() {
this.add(new BABYLON2.ArcRotateCameraVRDeviceOrientationInput());
return this;
};
return ArcRotateCameraInputsManager2;
}(BABYLON2.CameraInputsManager)
);
BABYLON2.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("ArcRotateCamera", function(name, scene) {
return function() {
return new ArcRotateCamera(name, 0, 0, 1, BABYLON2.Vector3.Zero(), scene);
};
});
var ArcRotateCamera = (
/** @class */
function(_super) {
__extends(ArcRotateCamera2, _super);
function ArcRotateCamera2(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) {
setActiveOnSceneIfNoneActive = true;
}
var _this = _super.call(this, name, BABYLON2.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
_this.inertialAlphaOffset = 0;
_this.inertialBetaOffset = 0;
_this.inertialRadiusOffset = 0;
_this.lowerAlphaLimit = null;
_this.upperAlphaLimit = null;
_this.lowerBetaLimit = 0.01;
_this.upperBetaLimit = Math.PI;
_this.lowerRadiusLimit = null;
_this.upperRadiusLimit = null;
_this.inertialPanningX = 0;
_this.inertialPanningY = 0;
_this.pinchToPanMaxDistance = 20;
_this.panningDistanceLimit = null;
_this.panningOriginTarget = BABYLON2.Vector3.Zero();
_this.panningInertia = 0.9;
_this.zoomOnFactor = 1;
_this.targetScreenOffset = BABYLON2.Vector2.Zero();
_this.allowUpsideDown = true;
_this.useInputToRestoreState = true;
_this._viewMatrix = new BABYLON2.Matrix();
_this.panningAxis = new BABYLON2.Vector3(1, 1, 0);
_this.onMeshTargetChangedObservable = new BABYLON2.Observable();
_this.checkCollisions = false;
_this.collisionRadius = new BABYLON2.Vector3(0.5, 0.5, 0.5);
_this._previousPosition = BABYLON2.Vector3.Zero();
_this._collisionVelocity = BABYLON2.Vector3.Zero();
_this._newPosition = BABYLON2.Vector3.Zero();
_this._computationVector = BABYLON2.Vector3.Zero();
_this._onCollisionPositionChange = function(collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) {
collidedMesh = null;
}
if (_this.getScene().workerCollisions && _this.checkCollisions) {
newPosition.multiplyInPlace(_this._collider._radius);
}
if (!collidedMesh) {
_this._previousPosition.copyFrom(_this.position);
} else {
_this.setPosition(newPosition);
if (_this.onCollide) {
_this.onCollide(collidedMesh);
}
}
var cosa = Math.cos(_this.alpha);
var sina = Math.sin(_this.alpha);
var cosb = Math.cos(_this.beta);
var sinb = Math.sin(_this.beta);
if (sinb === 0) {
sinb = 1e-4;
}
var target2 = _this._getTargetPosition();
_this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
target2.addToRef(_this._computationVector, _this._newPosition);
_this.position.copyFrom(_this._newPosition);
var up = _this.upVector;
if (_this.allowUpsideDown && _this.beta < 0) {
up = up.clone();
up = up.negate();
}
_this._computeViewMatrix(_this.position, target2, up);
_this._viewMatrix.m[12] += _this.targetScreenOffset.x;
_this._viewMatrix.m[13] += _this.targetScreenOffset.y;
_this._collisionTriggered = false;
};
_this._target = BABYLON2.Vector3.Zero();
if (target) {
_this.setTarget(target);
}
_this.alpha = alpha;
_this.beta = beta;
_this.radius = radius;
_this.getViewMatrix();
_this.inputs = new BABYLON2.ArcRotateCameraInputsManager(_this);
_this.inputs.addKeyboard().addMouseWheel().addPointers();
return _this;
}
Object.defineProperty(ArcRotateCamera2.prototype, "target", {
/**
* Defines the target point of the camera.
* The camera looks towards it form the radius distance.
*/
get: function() {
return this._target;
},
set: function(value) {
this.setTarget(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "angularSensibilityX", {
//-- begin properties for backward compatibility for inputs
/**
* Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
*/
get: function() {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.angularSensibilityX;
}
return 0;
},
set: function(value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.angularSensibilityX = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "angularSensibilityY", {
/**
* Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
*/
get: function() {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.angularSensibilityY;
}
return 0;
},
set: function(value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.angularSensibilityY = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "pinchPrecision", {
/**
* Gets or Set the pointer pinch precision or how fast is the camera zooming.
*/
get: function() {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.pinchPrecision;
}
return 0;
},
set: function(value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.pinchPrecision = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "pinchDeltaPercentage", {
/**
* Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
* It will be used instead of pinchDeltaPrecision if different from 0.
* It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
*/
get: function() {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.pinchDeltaPercentage;
}
return 0;
},
set: function(value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.pinchDeltaPercentage = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "panningSensibility", {
/**
* Gets or Set the pointer panning sensibility or how fast is the camera moving.
*/
get: function() {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.panningSensibility;
}
return 0;
},
set: function(value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.panningSensibility = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "keysUp", {
/**
* Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysUp;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysUp = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "keysDown", {
/**
* Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysDown;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysDown = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "keysLeft", {
/**
* Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysLeft;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysLeft = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "keysRight", {
/**
* Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
*/
get: function() {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysRight;
}
return [];
},
set: function(value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysRight = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "wheelPrecision", {
/**
* Gets or Set the mouse wheel precision or how fast is the camera zooming.
*/
get: function() {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
return mousewheel.wheelPrecision;
}
return 0;
},
set: function(value) {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
mousewheel.wheelPrecision = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "wheelDeltaPercentage", {
/**
* Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
* It will be used instead of pinchDeltaPrecision if different from 0.
* It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
*/
get: function() {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
return mousewheel.wheelDeltaPercentage;
}
return 0;
},
set: function(value) {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
mousewheel.wheelDeltaPercentage = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "bouncingBehavior", {
/**
* Gets the bouncing behavior of the camera if it has been enabled.
* @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
*/
get: function() {
return this._bouncingBehavior;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "useBouncingBehavior", {
/**
* Defines if the bouncing behavior of the camera is enabled on the camera.
* @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
*/
get: function() {
return this._bouncingBehavior != null;
},
set: function(value) {
if (value === this.useBouncingBehavior) {
return;
}
if (value) {
this._bouncingBehavior = new BABYLON2.BouncingBehavior();
this.addBehavior(this._bouncingBehavior);
} else if (this._bouncingBehavior) {
this.removeBehavior(this._bouncingBehavior);
this._bouncingBehavior = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "framingBehavior", {
/**
* Gets the framing behavior of the camera if it has been enabled.
* @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
*/
get: function() {
return this._framingBehavior;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "useFramingBehavior", {
/**
* Defines if the framing behavior of the camera is enabled on the camera.
* @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
*/
get: function() {
return this._framingBehavior != null;
},
set: function(value) {
if (value === this.useFramingBehavior) {
return;
}
if (value) {
this._framingBehavior = new BABYLON2.FramingBehavior();
this.addBehavior(this._framingBehavior);
} else if (this._framingBehavior) {
this.removeBehavior(this._framingBehavior);
this._framingBehavior = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "autoRotationBehavior", {
/**
* Gets the auto rotation behavior of the camera if it has been enabled.
* @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
*/
get: function() {
return this._autoRotationBehavior;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ArcRotateCamera2.prototype, "useAutoRotationBehavior", {
/**
* Defines if the auto rotation behavior of the camera is enabled on the camera.
* @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
*/
get: function() {
return this._autoRotationBehavior != null;
},
set: function(value) {
if (value === this.useAutoRotationBehavior) {
return;
}
if (value) {
this._autoRotationBehavior = new BABYLON2.AutoRotationBehavior();
this.addBehavior(this._autoRotationBehavior);
} else if (this._autoRotationBehavior) {
this.removeBehavior(this._autoRotationBehavior);
this._autoRotationBehavior = null;
}
},
enumerable: true,
configurable: true
});
ArcRotateCamera2.prototype._initCache = function() {
_super.prototype._initCache.call(this);
this._cache._target = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.alpha = void 0;
this._cache.beta = void 0;
this._cache.radius = void 0;
this._cache.targetScreenOffset = BABYLON2.Vector2.Zero();
};
ArcRotateCamera2.prototype._updateCache = function(ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
this._cache._target.copyFrom(this._getTargetPosition());
this._cache.alpha = this.alpha;
this._cache.beta = this.beta;
this._cache.radius = this.radius;
this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
};
ArcRotateCamera2.prototype._getTargetPosition = function() {
if (this._targetHost && this._targetHost.getAbsolutePosition) {
var pos = this._targetHost.getAbsolutePosition();
if (this._targetBoundingCenter) {
pos.addToRef(this._targetBoundingCenter, this._target);
} else {
this._target.copyFrom(pos);
}
}
var lockedTargetPosition = this._getLockedTargetPosition();
if (lockedTargetPosition) {
return lockedTargetPosition;
}
return this._target;
};
ArcRotateCamera2.prototype.storeState = function() {
this._storedAlpha = this.alpha;
this._storedBeta = this.beta;
this._storedRadius = this.radius;
this._storedTarget = this._getTargetPosition().clone();
return _super.prototype.storeState.call(this);
};
ArcRotateCamera2.prototype._restoreStateValues = function() {
if (!_super.prototype._restoreStateValues.call(this)) {
return false;
}
this.alpha = this._storedAlpha;
this.beta = this._storedBeta;
this.radius = this._storedRadius;
this.setTarget(this._storedTarget.clone());
this.inertialAlphaOffset = 0;
this.inertialBetaOffset = 0;
this.inertialRadiusOffset = 0;
this.inertialPanningX = 0;
this.inertialPanningY = 0;
return true;
};
ArcRotateCamera2.prototype._isSynchronizedViewMatrix = function() {
if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
return false;
}
return this._cache._target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
};
ArcRotateCamera2.prototype.attachControl = function(element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
var _this = this;
if (useCtrlForPanning === void 0) {
useCtrlForPanning = true;
}
if (panningMouseButton === void 0) {
panningMouseButton = 2;
}
this._useCtrlForPanning = useCtrlForPanning;
this._panningMouseButton = panningMouseButton;
this.inputs.attachElement(element, noPreventDefault);
this._reset = function() {
_this.inertialAlphaOffset = 0;
_this.inertialBetaOffset = 0;
_this.inertialRadiusOffset = 0;
_this.inertialPanningX = 0;
_this.inertialPanningY = 0;
};
};
ArcRotateCamera2.prototype.detachControl = function(element) {
this.inputs.detachElement(element);
if (this._reset) {
this._reset();
}
};
ArcRotateCamera2.prototype._checkInputs = function() {
if (this._collisionTriggered) {
return;
}
this.inputs.checkInputs();
if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
var inertialAlphaOffset = this.inertialAlphaOffset;
if (this.beta <= 0) {
inertialAlphaOffset *= -1;
}
if (this.getScene().useRightHandedSystem) {
inertialAlphaOffset *= -1;
}
if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
inertialAlphaOffset *= -1;
}
this.alpha += inertialAlphaOffset;
this.beta += this.inertialBetaOffset;
this.radius -= this.inertialRadiusOffset;
this.inertialAlphaOffset *= this.inertia;
this.inertialBetaOffset *= this.inertia;
this.inertialRadiusOffset *= this.inertia;
if (Math.abs(this.inertialAlphaOffset) < BABYLON2.Epsilon) {
this.inertialAlphaOffset = 0;
}
if (Math.abs(this.inertialBetaOffset) < BABYLON2.Epsilon) {
this.inertialBetaOffset = 0;
}
if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON2.Epsilon) {
this.inertialRadiusOffset = 0;
}
}
if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
if (!this._localDirection) {
this._localDirection = BABYLON2.Vector3.Zero();
this._transformedDirection = BABYLON2.Vector3.Zero();
}
this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
this._localDirection.multiplyInPlace(this.panningAxis);
this._viewMatrix.invertToRef(this._cameraTransformMatrix);
BABYLON2.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
if (!this.panningAxis.y) {
this._transformedDirection.y = 0;
}
if (!this._targetHost) {
if (this.panningDistanceLimit) {
this._transformedDirection.addInPlace(this._target);
var distanceSquared = BABYLON2.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
if (distanceSquared <= this.panningDistanceLimit * this.panningDistanceLimit) {
this._target.copyFrom(this._transformedDirection);
}
} else {
this._target.addInPlace(this._transformedDirection);
}
}
this.inertialPanningX *= this.panningInertia;
this.inertialPanningY *= this.panningInertia;
if (Math.abs(this.inertialPanningX) < this.speed * BABYLON2.Epsilon) {
this.inertialPanningX = 0;
}
if (Math.abs(this.inertialPanningY) < this.speed * BABYLON2.Epsilon) {
this.inertialPanningY = 0;
}
}
this._checkLimits();
_super.prototype._checkInputs.call(this);
};
ArcRotateCamera2.prototype._checkLimits = function() {
if (this.lowerBetaLimit === null || this.lowerBetaLimit === void 0) {
if (this.allowUpsideDown && this.beta > Math.PI) {
this.beta = this.beta - 2 * Math.PI;
}
} else {
if (this.beta < this.lowerBetaLimit) {
this.beta = this.lowerBetaLimit;
}
}
if (this.upperBetaLimit === null || this.upperBetaLimit === void 0) {
if (this.allowUpsideDown && this.beta < -Math.PI) {
this.beta = this.beta + 2 * Math.PI;
}
} else {
if (this.beta > this.upperBetaLimit) {
this.beta = this.upperBetaLimit;
}
}
if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
this.alpha = this.lowerAlphaLimit;
}
if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
this.alpha = this.upperAlphaLimit;
}
if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
this.radius = this.lowerRadiusLimit;
}
if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
this.radius = this.upperRadiusLimit;
}
};
ArcRotateCamera2.prototype.rebuildAnglesAndRadius = function() {
this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
this.radius = this._computationVector.length();
if (this.radius === 0) {
this.radius = 1e-4;
}
this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
if (this._computationVector.z < 0) {
this.alpha = 2 * Math.PI - this.alpha;
}
this.beta = Math.acos(this._computationVector.y / this.radius);
this._checkLimits();
};
ArcRotateCamera2.prototype.setPosition = function(position) {
if (this.position.equals(position)) {
return;
}
this.position.copyFrom(position);
this.rebuildAnglesAndRadius();
};
ArcRotateCamera2.prototype.setTarget = function(target, toBoundingCenter, allowSamePosition) {
if (toBoundingCenter === void 0) {
toBoundingCenter = false;
}
if (allowSamePosition === void 0) {
allowSamePosition = false;
}
if (target.getBoundingInfo) {
if (toBoundingCenter) {
this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
} else {
this._targetBoundingCenter = null;
}
this._targetHost = target;
this._target = this._getTargetPosition();
this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
} else {
var newTarget = target;
var currentTarget = this._getTargetPosition();
if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
return;
}
this._targetHost = null;
this._target = newTarget;
this._targetBoundingCenter = null;
this.onMeshTargetChangedObservable.notifyObservers(null);
}
this.rebuildAnglesAndRadius();
};
ArcRotateCamera2.prototype._getViewMatrix = function() {
var cosa = Math.cos(this.alpha);
var sina = Math.sin(this.alpha);
var cosb = Math.cos(this.beta);
var sinb = Math.sin(this.beta);
if (sinb === 0) {
sinb = 1e-4;
}
var target = this._getTargetPosition();
this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
target.addToRef(this._computationVector, this._newPosition);
if (this.getScene().collisionsEnabled && this.checkCollisions) {
if (!this._collider) {
this._collider = new BABYLON2.Collider();
}
this._collider._radius = this.collisionRadius;
this._newPosition.subtractToRef(this.position, this._collisionVelocity);
this._collisionTriggered = true;
this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
} else {
this.position.copyFrom(this._newPosition);
var up = this.upVector;
if (this.allowUpsideDown && sinb < 0) {
up = up.clone();
up = up.negate();
}
this._computeViewMatrix(this.position, target, up);
this._viewMatrix.m[12] += this.targetScreenOffset.x;
this._viewMatrix.m[13] += this.targetScreenOffset.y;
}
this._currentTarget = target;
return this._viewMatrix;
};
ArcRotateCamera2.prototype.zoomOn = function(meshes, doNotUpdateMaxZ) {
if (doNotUpdateMaxZ === void 0) {
doNotUpdateMaxZ = false;
}
meshes = meshes || this.getScene().meshes;
var minMaxVector = BABYLON2.Mesh.MinMax(meshes);
var distance = BABYLON2.Vector3.Distance(minMaxVector.min, minMaxVector.max);
this.radius = distance * this.zoomOnFactor;
this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance }, doNotUpdateMaxZ);
};
ArcRotateCamera2.prototype.focusOn = function(meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
if (doNotUpdateMaxZ === void 0) {
doNotUpdateMaxZ = false;
}
var meshesOrMinMaxVector;
var distance;
if (meshesOrMinMaxVectorAndDistance.min === void 0) {
var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
meshesOrMinMaxVector = BABYLON2.Mesh.MinMax(meshes);
distance = BABYLON2.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
} else {
var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
meshesOrMinMaxVector = minMaxVectorAndDistance;
distance = minMaxVectorAndDistance.distance;
}
this._target = BABYLON2.Mesh.Center(meshesOrMinMaxVector);
if (!doNotUpdateMaxZ) {
this.maxZ = distance * 2;
}
};
ArcRotateCamera2.prototype.createRigCamera = function(name, cameraIndex) {
var alphaShift = 0;
switch (this.cameraRigMode) {
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
case BABYLON2.Camera.RIG_MODE_VR:
alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
break;
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
break;
}
var rigCam = new ArcRotateCamera2(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
rigCam._cameraRigParams = {};
return rigCam;
};
ArcRotateCamera2.prototype._updateRigCameras = function() {
var camLeft = this._rigCameras[0];
var camRight = this._rigCameras[1];
camLeft.beta = camRight.beta = this.beta;
camLeft.radius = camRight.radius = this.radius;
switch (this.cameraRigMode) {
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
case BABYLON2.Camera.RIG_MODE_VR:
camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
break;
case BABYLON2.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
break;
}
_super.prototype._updateRigCameras.call(this);
};
ArcRotateCamera2.prototype.dispose = function() {
this.inputs.clear();
_super.prototype.dispose.call(this);
};
ArcRotateCamera2.prototype.getClassName = function() {
return "ArcRotateCamera";
};
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "alpha", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "beta", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "radius", void 0);
__decorate([
BABYLON2.serializeAsVector3("target")
], ArcRotateCamera2.prototype, "_target", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "inertialAlphaOffset", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "inertialBetaOffset", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "inertialRadiusOffset", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "lowerAlphaLimit", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "upperAlphaLimit", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "lowerBetaLimit", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "upperBetaLimit", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "lowerRadiusLimit", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "upperRadiusLimit", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "inertialPanningX", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "inertialPanningY", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "pinchToPanMaxDistance", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "panningDistanceLimit", void 0);
__decorate([
BABYLON2.serializeAsVector3()
], ArcRotateCamera2.prototype, "panningOriginTarget", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "panningInertia", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "zoomOnFactor", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "targetScreenOffset", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "allowUpsideDown", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCamera2.prototype, "useInputToRestoreState", void 0);
return ArcRotateCamera2;
}(BABYLON2.TargetCamera)
);
BABYLON2.ArcRotateCamera = ArcRotateCamera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("Light_Type_3", function(name, scene) {
return function() {
return new HemisphericLight(name, BABYLON2.Vector3.Zero(), scene);
};
});
var HemisphericLight = (
/** @class */
function(_super) {
__extends(HemisphericLight2, _super);
function HemisphericLight2(name, direction, scene) {
var _this = _super.call(this, name, scene) || this;
_this.groundColor = new BABYLON2.Color3(0, 0, 0);
_this.direction = direction || BABYLON2.Vector3.Up();
return _this;
}
HemisphericLight2.prototype._buildUniformLayout = function() {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("vLightGround", 3);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
HemisphericLight2.prototype.getClassName = function() {
return "HemisphericLight";
};
HemisphericLight2.prototype.setDirectionToTarget = function(target) {
this.direction = BABYLON2.Vector3.Normalize(target.subtract(BABYLON2.Vector3.Zero()));
return this.direction;
};
HemisphericLight2.prototype.getShadowGenerator = function() {
return null;
};
HemisphericLight2.prototype.transferToEffect = function(effect, lightIndex) {
var normalizeDirection = BABYLON2.Vector3.Normalize(this.direction);
this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0, lightIndex);
this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
return this;
};
HemisphericLight2.prototype.computeWorldMatrix = function(force, useWasUpdatedFlag) {
if (!this._worldMatrix) {
this._worldMatrix = BABYLON2.Matrix.Identity();
}
return this._worldMatrix;
};
HemisphericLight2.prototype.getTypeID = function() {
return BABYLON2.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
};
HemisphericLight2.prototype.prepareLightSpecificDefines = function(defines, lightIndex) {
defines["HEMILIGHT" + lightIndex] = true;
};
__decorate([
BABYLON2.serializeAsColor3()
], HemisphericLight2.prototype, "groundColor", void 0);
__decorate([
BABYLON2.serializeAsVector3()
], HemisphericLight2.prototype, "direction", void 0);
return HemisphericLight2;
}(BABYLON2.Light)
);
BABYLON2.HemisphericLight = HemisphericLight;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ShadowLight = (
/** @class */
function(_super) {
__extends(ShadowLight2, _super);
function ShadowLight2() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._needProjectionMatrixCompute = true;
return _this;
}
ShadowLight2.prototype._setPosition = function(value) {
this._position = value;
};
Object.defineProperty(ShadowLight2.prototype, "position", {
/**
* Sets the position the shadow will be casted from. Also use as the light position for both
* point and spot lights.
*/
get: function() {
return this._position;
},
/**
* Sets the position the shadow will be casted from. Also use as the light position for both
* point and spot lights.
*/
set: function(value) {
this._setPosition(value);
},
enumerable: true,
configurable: true
});
ShadowLight2.prototype._setDirection = function(value) {
this._direction = value;
};
Object.defineProperty(ShadowLight2.prototype, "direction", {
/**
* In 2d mode (needCube being false), gets the direction used to cast the shadow.
* Also use as the light direction on spot and directional lights.
*/
get: function() {
return this._direction;
},
/**
* In 2d mode (needCube being false), sets the direction used to cast the shadow.
* Also use as the light direction on spot and directional lights.
*/
set: function(value) {
this._setDirection(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowLight2.prototype, "shadowMinZ", {
/**
* Gets the shadow projection clipping minimum z value.
*/
get: function() {
return this._shadowMinZ;
},
/**
* Sets the shadow projection clipping minimum z value.
*/
set: function(value) {
this._shadowMinZ = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowLight2.prototype, "shadowMaxZ", {
/**
* Sets the shadow projection clipping maximum z value.
*/
get: function() {
return this._shadowMaxZ;
},
/**
* Gets the shadow projection clipping maximum z value.
*/
set: function(value) {
this._shadowMaxZ = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
ShadowLight2.prototype.computeTransformedInformation = function() {
if (this.parent && this.parent.getWorldMatrix) {
if (!this.transformedPosition) {
this.transformedPosition = BABYLON2.Vector3.Zero();
}
BABYLON2.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
if (this.direction) {
if (!this.transformedDirection) {
this.transformedDirection = BABYLON2.Vector3.Zero();
}
BABYLON2.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
}
return true;
}
return false;
};
ShadowLight2.prototype.getDepthScale = function() {
return 50;
};
ShadowLight2.prototype.getShadowDirection = function(faceIndex) {
return this.transformedDirection ? this.transformedDirection : this.direction;
};
ShadowLight2.prototype.getAbsolutePosition = function() {
return this.transformedPosition ? this.transformedPosition : this.position;
};
ShadowLight2.prototype.setDirectionToTarget = function(target) {
this.direction = BABYLON2.Vector3.Normalize(target.subtract(this.position));
return this.direction;
};
ShadowLight2.prototype.getRotation = function() {
this.direction.normalize();
var xaxis = BABYLON2.Vector3.Cross(this.direction, BABYLON2.Axis.Y);
var yaxis = BABYLON2.Vector3.Cross(xaxis, this.direction);
return BABYLON2.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
};
ShadowLight2.prototype.needCube = function() {
return false;
};
ShadowLight2.prototype.needProjectionMatrixCompute = function() {
return this._needProjectionMatrixCompute;
};
ShadowLight2.prototype.forceProjectionMatrixCompute = function() {
this._needProjectionMatrixCompute = true;
};
ShadowLight2.prototype._initCache = function() {
_super.prototype._initCache.call(this);
this._cache.position = BABYLON2.Vector3.Zero();
};
ShadowLight2.prototype._isSynchronized = function() {
if (!this._cache.position.equals(this.position)) {
return false;
}
return true;
};
ShadowLight2.prototype.computeWorldMatrix = function(force) {
if (!force && this.isSynchronized()) {
this._currentRenderId = this.getScene().getRenderId();
return this._worldMatrix;
}
this._updateCache();
this._cache.position.copyFrom(this.position);
if (!this._worldMatrix) {
this._worldMatrix = BABYLON2.Matrix.Identity();
}
BABYLON2.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
if (this.parent && this.parent.getWorldMatrix) {
this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
this._markSyncedWithParent();
}
this._worldMatrixDeterminant = this._worldMatrix.determinant();
return this._worldMatrix;
};
ShadowLight2.prototype.getDepthMinZ = function(activeCamera) {
return this.shadowMinZ !== void 0 ? this.shadowMinZ : activeCamera.minZ;
};
ShadowLight2.prototype.getDepthMaxZ = function(activeCamera) {
return this.shadowMaxZ !== void 0 ? this.shadowMaxZ : activeCamera.maxZ;
};
ShadowLight2.prototype.setShadowProjectionMatrix = function(matrix, viewMatrix, renderList) {
if (this.customProjectionMatrixBuilder) {
this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
} else {
this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
}
return this;
};
__decorate([
BABYLON2.serializeAsVector3()
], ShadowLight2.prototype, "position", null);
__decorate([
BABYLON2.serializeAsVector3()
], ShadowLight2.prototype, "direction", null);
__decorate([
BABYLON2.serialize()
], ShadowLight2.prototype, "shadowMinZ", null);
__decorate([
BABYLON2.serialize()
], ShadowLight2.prototype, "shadowMaxZ", null);
return ShadowLight2;
}(BABYLON2.Light)
);
BABYLON2.ShadowLight = ShadowLight;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("Light_Type_0", function(name, scene) {
return function() {
return new PointLight(name, BABYLON2.Vector3.Zero(), scene);
};
});
var PointLight = (
/** @class */
function(_super) {
__extends(PointLight2, _super);
function PointLight2(name, position, scene) {
var _this = _super.call(this, name, scene) || this;
_this._shadowAngle = Math.PI / 2;
_this.position = position;
return _this;
}
Object.defineProperty(PointLight2.prototype, "shadowAngle", {
/**
* Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
* This specifies what angle the shadow will use to be created.
*
* It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
*/
get: function() {
return this._shadowAngle;
},
/**
* Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
* This specifies what angle the shadow will use to be created.
*
* It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
*/
set: function(value) {
this._shadowAngle = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(PointLight2.prototype, "direction", {
/**
* Gets the direction if it has been set.
* In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
*/
get: function() {
return this._direction;
},
/**
* In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
*/
set: function(value) {
var previousNeedCube = this.needCube();
this._direction = value;
if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
this._shadowGenerator.recreateShadowMap();
}
},
enumerable: true,
configurable: true
});
PointLight2.prototype.getClassName = function() {
return "PointLight";
};
PointLight2.prototype.getTypeID = function() {
return BABYLON2.Light.LIGHTTYPEID_POINTLIGHT;
};
PointLight2.prototype.needCube = function() {
return !this.direction;
};
PointLight2.prototype.getShadowDirection = function(faceIndex) {
if (this.direction) {
return _super.prototype.getShadowDirection.call(this, faceIndex);
} else {
switch (faceIndex) {
case 0:
return new BABYLON2.Vector3(1, 0, 0);
case 1:
return new BABYLON2.Vector3(-1, 0, 0);
case 2:
return new BABYLON2.Vector3(0, -1, 0);
case 3:
return new BABYLON2.Vector3(0, 1, 0);
case 4:
return new BABYLON2.Vector3(0, 0, 1);
case 5:
return new BABYLON2.Vector3(0, 0, -1);
}
}
return BABYLON2.Vector3.Zero();
};
PointLight2.prototype._setDefaultShadowProjectionMatrix = function(matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
BABYLON2.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
};
PointLight2.prototype._buildUniformLayout = function() {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("vLightFalloff", 4);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
PointLight2.prototype.transferToEffect = function(effect, lightIndex) {
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0, lightIndex);
} else {
this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
}
this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
return this;
};
PointLight2.prototype.prepareLightSpecificDefines = function(defines, lightIndex) {
defines["POINTLIGHT" + lightIndex] = true;
};
__decorate([
BABYLON2.serialize()
], PointLight2.prototype, "shadowAngle", null);
return PointLight2;
}(BABYLON2.ShadowLight)
);
BABYLON2.PointLight = PointLight;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("Light_Type_1", function(name, scene) {
return function() {
return new DirectionalLight(name, BABYLON2.Vector3.Zero(), scene);
};
});
var DirectionalLight = (
/** @class */
function(_super) {
__extends(DirectionalLight2, _super);
function DirectionalLight2(name, direction, scene) {
var _this = _super.call(this, name, scene) || this;
_this._shadowFrustumSize = 0;
_this._shadowOrthoScale = 0.1;
_this.autoUpdateExtends = true;
_this._orthoLeft = Number.MAX_VALUE;
_this._orthoRight = Number.MIN_VALUE;
_this._orthoTop = Number.MIN_VALUE;
_this._orthoBottom = Number.MAX_VALUE;
_this.position = direction.scale(-1);
_this.direction = direction;
return _this;
}
Object.defineProperty(DirectionalLight2.prototype, "shadowFrustumSize", {
/**
* Fix frustum size for the shadow generation. This is disabled if the value is 0.
*/
get: function() {
return this._shadowFrustumSize;
},
/**
* Specifies a fix frustum size for the shadow generation.
*/
set: function(value) {
this._shadowFrustumSize = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DirectionalLight2.prototype, "shadowOrthoScale", {
/**
* Gets the shadow projection scale against the optimal computed one.
* 0.1 by default which means that the projection window is increase by 10% from the optimal size.
* This does not impact in fixed frustum size (shadowFrustumSize being set)
*/
get: function() {
return this._shadowOrthoScale;
},
/**
* Sets the shadow projection scale against the optimal computed one.
* 0.1 by default which means that the projection window is increase by 10% from the optimal size.
* This does not impact in fixed frustum size (shadowFrustumSize being set)
*/
set: function(value) {
this._shadowOrthoScale = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
DirectionalLight2.prototype.getClassName = function() {
return "DirectionalLight";
};
DirectionalLight2.prototype.getTypeID = function() {
return BABYLON2.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
};
DirectionalLight2.prototype._setDefaultShadowProjectionMatrix = function(matrix, viewMatrix, renderList) {
if (this.shadowFrustumSize > 0) {
this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
} else {
this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
}
};
DirectionalLight2.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function(matrix, viewMatrix) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
BABYLON2.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== void 0 ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== void 0 ? this.shadowMaxZ : activeCamera.maxZ, matrix);
};
DirectionalLight2.prototype._setDefaultAutoExtendShadowProjectionMatrix = function(matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
var tempVector3 = BABYLON2.Vector3.Zero();
this._orthoLeft = Number.MAX_VALUE;
this._orthoRight = Number.MIN_VALUE;
this._orthoTop = Number.MIN_VALUE;
this._orthoBottom = Number.MAX_VALUE;
for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
var mesh2 = renderList[meshIndex];
if (!mesh2) {
continue;
}
var boundingInfo = mesh2.getBoundingInfo();
var boundingBox = boundingInfo.boundingBox;
for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
BABYLON2.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
if (tempVector3.x < this._orthoLeft) {
this._orthoLeft = tempVector3.x;
}
if (tempVector3.y < this._orthoBottom) {
this._orthoBottom = tempVector3.y;
}
if (tempVector3.x > this._orthoRight) {
this._orthoRight = tempVector3.x;
}
if (tempVector3.y > this._orthoTop) {
this._orthoTop = tempVector3.y;
}
}
}
}
var xOffset = this._orthoRight - this._orthoLeft;
var yOffset = this._orthoTop - this._orthoBottom;
BABYLON2.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== void 0 ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== void 0 ? this.shadowMaxZ : activeCamera.maxZ, matrix);
};
DirectionalLight2.prototype._buildUniformLayout = function() {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
DirectionalLight2.prototype.transferToEffect = function(effect, lightIndex) {
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
return this;
}
this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
return this;
};
DirectionalLight2.prototype.getDepthMinZ = function(activeCamera) {
return 1;
};
DirectionalLight2.prototype.getDepthMaxZ = function(activeCamera) {
return 1;
};
DirectionalLight2.prototype.prepareLightSpecificDefines = function(defines, lightIndex) {
defines["DIRLIGHT" + lightIndex] = true;
};
__decorate([
BABYLON2.serialize()
], DirectionalLight2.prototype, "shadowFrustumSize", null);
__decorate([
BABYLON2.serialize()
], DirectionalLight2.prototype, "shadowOrthoScale", null);
__decorate([
BABYLON2.serialize()
], DirectionalLight2.prototype, "autoUpdateExtends", void 0);
return DirectionalLight2;
}(BABYLON2.ShadowLight)
);
BABYLON2.DirectionalLight = DirectionalLight;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("Light_Type_2", function(name, scene) {
return function() {
return new SpotLight(name, BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), 0, 0, scene);
};
});
var SpotLight = (
/** @class */
function(_super) {
__extends(SpotLight2, _super);
function SpotLight2(name, position, direction, angle, exponent, scene) {
var _this = _super.call(this, name, scene) || this;
_this._innerAngle = 0;
_this._projectionTextureMatrix = BABYLON2.Matrix.Zero();
_this._projectionTextureLightNear = 1e-6;
_this._projectionTextureLightFar = 1e3;
_this._projectionTextureUpDirection = BABYLON2.Vector3.Up();
_this._projectionTextureViewLightDirty = true;
_this._projectionTextureProjectionLightDirty = true;
_this._projectionTextureDirty = true;
_this._projectionTextureViewTargetVector = BABYLON2.Vector3.Zero();
_this._projectionTextureViewLightMatrix = BABYLON2.Matrix.Zero();
_this._projectionTextureProjectionLightMatrix = BABYLON2.Matrix.Zero();
_this._projectionTextureScalingMatrix = BABYLON2.Matrix.FromValues(0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0.5, 0.5, 0.5, 1);
_this.position = position;
_this.direction = direction;
_this.angle = angle;
_this.exponent = exponent;
return _this;
}
Object.defineProperty(SpotLight2.prototype, "angle", {
/**
* Gets the cone angle of the spot light in Radians.
*/
get: function() {
return this._angle;
},
/**
* Sets the cone angle of the spot light in Radians.
*/
set: function(value) {
this._angle = value;
this._cosHalfAngle = Math.cos(value * 0.5);
this._projectionTextureProjectionLightDirty = true;
this.forceProjectionMatrixCompute();
this._computeAngleValues();
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight2.prototype, "innerAngle", {
/**
* Only used in gltf falloff mode, this defines the angle where
* the directional falloff will start before cutting at angle which could be seen
* as outer angle.
*/
get: function() {
return this._innerAngle;
},
/**
* Only used in gltf falloff mode, this defines the angle where
* the directional falloff will start before cutting at angle which could be seen
* as outer angle.
*/
set: function(value) {
this._innerAngle = value;
this._computeAngleValues();
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight2.prototype, "shadowAngleScale", {
/**
* Allows scaling the angle of the light for shadow generation only.
*/
get: function() {
return this._shadowAngleScale;
},
/**
* Allows scaling the angle of the light for shadow generation only.
*/
set: function(value) {
this._shadowAngleScale = value;
this.forceProjectionMatrixCompute();
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight2.prototype, "projectionTextureMatrix", {
/**
* Allows reading the projecton texture
*/
get: function() {
return this._projectionTextureMatrix;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight2.prototype, "projectionTextureLightNear", {
/**
* Gets the near clip of the Spotlight for texture projection.
*/
get: function() {
return this._projectionTextureLightNear;
},
/**
* Sets the near clip of the Spotlight for texture projection.
*/
set: function(value) {
this._projectionTextureLightNear = value;
this._projectionTextureProjectionLightDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight2.prototype, "projectionTextureLightFar", {
/**
* Gets the far clip of the Spotlight for texture projection.
*/
get: function() {
return this._projectionTextureLightFar;
},
/**
* Sets the far clip of the Spotlight for texture projection.
*/
set: function(value) {
this._projectionTextureLightFar = value;
this._projectionTextureProjectionLightDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight2.prototype, "projectionTextureUpDirection", {
/**
* Gets the Up vector of the Spotlight for texture projection.
*/
get: function() {
return this._projectionTextureUpDirection;
},
/**
* Sets the Up vector of the Spotlight for texture projection.
*/
set: function(value) {
this._projectionTextureUpDirection = value;
this._projectionTextureProjectionLightDirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpotLight2.prototype, "projectionTexture", {
/**
* Gets the projection texture of the light.
*/
get: function() {
return this._projectionTexture;
},
/**
* Sets the projection texture of the light.
*/
set: function(value) {
this._projectionTexture = value;
this._projectionTextureDirty = true;
},
enumerable: true,
configurable: true
});
SpotLight2.prototype.getClassName = function() {
return "SpotLight";
};
SpotLight2.prototype.getTypeID = function() {
return BABYLON2.Light.LIGHTTYPEID_SPOTLIGHT;
};
SpotLight2.prototype._setDirection = function(value) {
_super.prototype._setDirection.call(this, value);
this._projectionTextureViewLightDirty = true;
};
SpotLight2.prototype._setPosition = function(value) {
_super.prototype._setPosition.call(this, value);
this._projectionTextureViewLightDirty = true;
};
SpotLight2.prototype._setDefaultShadowProjectionMatrix = function(matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
this._shadowAngleScale = this._shadowAngleScale || 1;
var angle = this._shadowAngleScale * this._angle;
BABYLON2.Matrix.PerspectiveFovLHToRef(angle, 1, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
};
SpotLight2.prototype._computeProjectionTextureViewLightMatrix = function() {
this._projectionTextureViewLightDirty = false;
this._projectionTextureDirty = true;
this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
BABYLON2.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
};
SpotLight2.prototype._computeProjectionTextureProjectionLightMatrix = function() {
this._projectionTextureProjectionLightDirty = false;
this._projectionTextureDirty = true;
var light_far = this.projectionTextureLightFar;
var light_near = this.projectionTextureLightNear;
var P = light_far / (light_far - light_near);
var Q = -P * light_near;
var S = 1 / Math.tan(this._angle / 2);
var A = 1;
BABYLON2.Matrix.FromValuesToRef(S / A, 0, 0, 0, 0, S, 0, 0, 0, 0, P, 1, 0, 0, Q, 0, this._projectionTextureProjectionLightMatrix);
};
SpotLight2.prototype._computeProjectionTextureMatrix = function() {
this._projectionTextureDirty = false;
this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
};
SpotLight2.prototype._buildUniformLayout = function() {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 3);
this._uniformBuffer.addUniform("vLightDirection", 3);
this._uniformBuffer.addUniform("vLightFalloff", 4);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
SpotLight2.prototype._computeAngleValues = function() {
this._lightAngleScale = 1 / Math.max(1e-3, Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle);
this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
};
SpotLight2.prototype.transferToEffect = function(effect, lightIndex) {
var normalizeDirection;
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
normalizeDirection = BABYLON2.Vector3.Normalize(this.transformedDirection);
} else {
this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
normalizeDirection = BABYLON2.Vector3.Normalize(this.direction);
}
this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
if (this.projectionTexture && this.projectionTexture.isReady()) {
if (this._projectionTextureViewLightDirty) {
this._computeProjectionTextureViewLightMatrix();
}
if (this._projectionTextureProjectionLightDirty) {
this._computeProjectionTextureProjectionLightMatrix();
}
if (this._projectionTextureDirty) {
this._computeProjectionTextureMatrix();
}
effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
}
return this;
};
SpotLight2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
if (this._projectionTexture) {
this._projectionTexture.dispose();
}
};
SpotLight2.prototype.prepareLightSpecificDefines = function(defines, lightIndex) {
defines["SPOTLIGHT" + lightIndex] = true;
defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
};
__decorate([
BABYLON2.serialize()
], SpotLight2.prototype, "angle", null);
__decorate([
BABYLON2.serialize()
], SpotLight2.prototype, "innerAngle", null);
__decorate([
BABYLON2.serialize()
], SpotLight2.prototype, "shadowAngleScale", null);
__decorate([
BABYLON2.serialize()
], SpotLight2.prototype, "exponent", void 0);
__decorate([
BABYLON2.serialize()
], SpotLight2.prototype, "projectionTextureLightNear", null);
__decorate([
BABYLON2.serialize()
], SpotLight2.prototype, "projectionTextureLightFar", null);
__decorate([
BABYLON2.serialize()
], SpotLight2.prototype, "projectionTextureUpDirection", null);
__decorate([
BABYLON2.serializeAsTexture("projectedLightTexture")
], SpotLight2.prototype, "_projectionTexture", void 0);
return SpotLight2;
}(BABYLON2.ShadowLight)
);
BABYLON2.SpotLight = SpotLight;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var AnimationPropertiesOverride = (
/** @class */
function() {
function AnimationPropertiesOverride2() {
this.enableBlending = false;
this.blendingSpeed = 0.01;
this.loopMode = BABYLON2.Animation.ANIMATIONLOOPMODE_CYCLE;
}
return AnimationPropertiesOverride2;
}()
);
BABYLON2.AnimationPropertiesOverride = AnimationPropertiesOverride;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var AnimationRange = (
/** @class */
function() {
function AnimationRange2(name, from, to) {
this.name = name;
this.from = from;
this.to = to;
}
AnimationRange2.prototype.clone = function() {
return new AnimationRange2(this.name, this.from, this.to);
};
return AnimationRange2;
}()
);
BABYLON2.AnimationRange = AnimationRange;
var AnimationEvent = (
/** @class */
function() {
function AnimationEvent2(frame, action, onlyOnce) {
this.frame = frame;
this.action = action;
this.onlyOnce = onlyOnce;
this.isDone = false;
}
AnimationEvent2.prototype._clone = function() {
return new AnimationEvent2(this.frame, this.action, this.onlyOnce);
};
return AnimationEvent2;
}()
);
BABYLON2.AnimationEvent = AnimationEvent;
var PathCursor = (
/** @class */
function() {
function PathCursor2(path) {
this.path = path;
this._onchange = new Array();
this.value = 0;
this.animations = new Array();
}
PathCursor2.prototype.getPoint = function() {
var point = this.path.getPointAtLengthPosition(this.value);
return new BABYLON2.Vector3(point.x, 0, point.y);
};
PathCursor2.prototype.moveAhead = function(step) {
if (step === void 0) {
step = 2e-3;
}
this.move(step);
return this;
};
PathCursor2.prototype.moveBack = function(step) {
if (step === void 0) {
step = 2e-3;
}
this.move(-step);
return this;
};
PathCursor2.prototype.move = function(step) {
if (Math.abs(step) > 1) {
throw "step size should be less than 1.";
}
this.value += step;
this.ensureLimits();
this.raiseOnChange();
return this;
};
PathCursor2.prototype.ensureLimits = function() {
while (this.value > 1) {
this.value -= 1;
}
while (this.value < 0) {
this.value += 1;
}
return this;
};
PathCursor2.prototype.raiseOnChange = function() {
var _this = this;
this._onchange.forEach(function(f) {
return f(_this);
});
return this;
};
PathCursor2.prototype.onchange = function(f) {
this._onchange.push(f);
return this;
};
return PathCursor2;
}()
);
BABYLON2.PathCursor = PathCursor;
var AnimationKeyInterpolation;
(function(AnimationKeyInterpolation2) {
AnimationKeyInterpolation2[AnimationKeyInterpolation2["STEP"] = 1] = "STEP";
})(AnimationKeyInterpolation = BABYLON2.AnimationKeyInterpolation || (BABYLON2.AnimationKeyInterpolation = {}));
var Animation = (
/** @class */
function() {
function Animation2(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
this.name = name;
this.targetProperty = targetProperty;
this.framePerSecond = framePerSecond;
this.dataType = dataType;
this.loopMode = loopMode;
this.enableBlending = enableBlending;
this._runtimeAnimations = new Array();
this._events = new Array();
this.blendingSpeed = 0.01;
this._ranges = {};
this.targetPropertyPath = targetProperty.split(".");
this.dataType = dataType;
this.loopMode = loopMode === void 0 ? Animation2.ANIMATIONLOOPMODE_CYCLE : loopMode;
}
Animation2._PrepareAnimation = function(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
var dataType = void 0;
if (!isNaN(parseFloat(from)) && isFinite(from)) {
dataType = Animation2.ANIMATIONTYPE_FLOAT;
} else if (from instanceof BABYLON2.Quaternion) {
dataType = Animation2.ANIMATIONTYPE_QUATERNION;
} else if (from instanceof BABYLON2.Vector3) {
dataType = Animation2.ANIMATIONTYPE_VECTOR3;
} else if (from instanceof BABYLON2.Vector2) {
dataType = Animation2.ANIMATIONTYPE_VECTOR2;
} else if (from instanceof BABYLON2.Color3) {
dataType = Animation2.ANIMATIONTYPE_COLOR3;
} else if (from instanceof BABYLON2.Size) {
dataType = Animation2.ANIMATIONTYPE_SIZE;
}
if (dataType == void 0) {
return null;
}
var animation = new Animation2(name, targetProperty, framePerSecond, dataType, loopMode);
var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
animation.setKeys(keys);
if (easingFunction !== void 0) {
animation.setEasingFunction(easingFunction);
}
return animation;
};
Animation2.CreateAnimation = function(property, animationType, framePerSecond, easingFunction) {
var animation = new Animation2(property + "Animation", property, framePerSecond, animationType, Animation2.ANIMATIONLOOPMODE_CONSTANT);
animation.setEasingFunction(easingFunction);
return animation;
};
Animation2.CreateAndStartAnimation = function(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
var animation = Animation2._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
if (!animation) {
return null;
}
return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, animation.loopMode === 1, 1, onAnimationEnd);
};
Animation2.CreateAndStartHierarchyAnimation = function(name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
var animation = Animation2._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
if (!animation) {
return null;
}
var scene = node.getScene();
return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, animation.loopMode === 1, 1, onAnimationEnd);
};
Animation2.CreateMergeAndStartAnimation = function(name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
var animation = Animation2._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
if (!animation) {
return null;
}
node.animations.push(animation);
return node.getScene().beginAnimation(node, 0, totalFrame, animation.loopMode === 1, 1, onAnimationEnd);
};
Animation2.TransitionTo = function(property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
if (onAnimationEnd === void 0) {
onAnimationEnd = null;
}
if (duration <= 0) {
host[property] = targetValue;
if (onAnimationEnd) {
onAnimationEnd();
}
return null;
}
var endFrame = frameRate * (duration / 1e3);
transition.setKeys([
{
frame: 0,
value: host[property].clone ? host[property].clone() : host[property]
},
{
frame: endFrame,
value: targetValue
}
]);
if (!host.animations) {
host.animations = [];
}
host.animations.push(transition);
var animation = scene.beginAnimation(host, 0, endFrame, false);
animation.onAnimationEnd = onAnimationEnd;
return animation;
};
Object.defineProperty(Animation2.prototype, "runtimeAnimations", {
/**
* Return the array of runtime animations currently using this animation
*/
get: function() {
return this._runtimeAnimations;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2.prototype, "hasRunningRuntimeAnimations", {
/**
* Specifies if any of the runtime animations are currently running
*/
get: function() {
for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
var runtimeAnimation = _a[_i];
if (!runtimeAnimation.isStopped) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
Animation2.prototype.toString = function(fullDetails) {
var ret = "Name: " + this.name + ", property: " + this.targetProperty;
ret += ", datatype: " + ["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"][this.dataType];
ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
if (fullDetails) {
ret += ", Ranges: {";
var first = true;
for (var name in this._ranges) {
if (first) {
ret += ", ";
first = false;
}
ret += name;
}
ret += "}";
}
return ret;
};
Animation2.prototype.addEvent = function(event) {
this._events.push(event);
};
Animation2.prototype.removeEvents = function(frame) {
for (var index = 0; index < this._events.length; index++) {
if (this._events[index].frame === frame) {
this._events.splice(index, 1);
index--;
}
}
};
Animation2.prototype.getEvents = function() {
return this._events;
};
Animation2.prototype.createRange = function(name, from, to) {
if (!this._ranges[name]) {
this._ranges[name] = new AnimationRange(name, from, to);
}
};
Animation2.prototype.deleteRange = function(name, deleteFrames) {
if (deleteFrames === void 0) {
deleteFrames = true;
}
var range = this._ranges[name];
if (!range) {
return;
}
if (deleteFrames) {
var from = range.from;
var to = range.to;
for (var key = this._keys.length - 1; key >= 0; key--) {
if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
this._keys.splice(key, 1);
}
}
}
this._ranges[name] = null;
};
Animation2.prototype.getRange = function(name) {
return this._ranges[name];
};
Animation2.prototype.getKeys = function() {
return this._keys;
};
Animation2.prototype.getHighestFrame = function() {
var ret = 0;
for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
if (ret < this._keys[key].frame) {
ret = this._keys[key].frame;
}
}
return ret;
};
Animation2.prototype.getEasingFunction = function() {
return this._easingFunction;
};
Animation2.prototype.setEasingFunction = function(easingFunction) {
this._easingFunction = easingFunction;
};
Animation2.prototype.floatInterpolateFunction = function(startValue, endValue, gradient) {
return BABYLON2.Scalar.Lerp(startValue, endValue, gradient);
};
Animation2.prototype.floatInterpolateFunctionWithTangents = function(startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON2.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
};
Animation2.prototype.quaternionInterpolateFunction = function(startValue, endValue, gradient) {
return BABYLON2.Quaternion.Slerp(startValue, endValue, gradient);
};
Animation2.prototype.quaternionInterpolateFunctionWithTangents = function(startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON2.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
};
Animation2.prototype.vector3InterpolateFunction = function(startValue, endValue, gradient) {
return BABYLON2.Vector3.Lerp(startValue, endValue, gradient);
};
Animation2.prototype.vector3InterpolateFunctionWithTangents = function(startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON2.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
};
Animation2.prototype.vector2InterpolateFunction = function(startValue, endValue, gradient) {
return BABYLON2.Vector2.Lerp(startValue, endValue, gradient);
};
Animation2.prototype.vector2InterpolateFunctionWithTangents = function(startValue, outTangent, endValue, inTangent, gradient) {
return BABYLON2.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
};
Animation2.prototype.sizeInterpolateFunction = function(startValue, endValue, gradient) {
return BABYLON2.Size.Lerp(startValue, endValue, gradient);
};
Animation2.prototype.color3InterpolateFunction = function(startValue, endValue, gradient) {
return BABYLON2.Color3.Lerp(startValue, endValue, gradient);
};
Animation2.prototype._getKeyValue = function(value) {
if (typeof value === "function") {
return value();
}
return value;
};
Animation2.prototype._interpolate = function(currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
if (loopMode === Animation2.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
}
var keys = this.getKeys();
var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
if (keys[startKeyIndex].frame >= currentFrame) {
while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
startKeyIndex--;
}
}
for (var key = startKeyIndex; key < keys.length; key++) {
var endKey = keys[key + 1];
if (endKey.frame >= currentFrame) {
var startKey = keys[key];
var startValue = this._getKeyValue(startKey.value);
if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
return startValue;
}
var endValue = this._getKeyValue(endKey.value);
var useTangent = startKey.outTangent !== void 0 && endKey.inTangent !== void 0;
var frameDelta = endKey.frame - startKey.frame;
var gradient = (currentFrame - startKey.frame) / frameDelta;
var easingFunction = this.getEasingFunction();
if (easingFunction != null) {
gradient = easingFunction.ease(gradient);
}
switch (this.dataType) {
case Animation2.ANIMATIONTYPE_FLOAT:
var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
switch (loopMode) {
case Animation2.ANIMATIONLOOPMODE_CYCLE:
case Animation2.ANIMATIONLOOPMODE_CONSTANT:
return floatValue;
case Animation2.ANIMATIONLOOPMODE_RELATIVE:
return offsetValue * repeatCount + floatValue;
}
break;
case Animation2.ANIMATIONTYPE_QUATERNION:
var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
switch (loopMode) {
case Animation2.ANIMATIONLOOPMODE_CYCLE:
case Animation2.ANIMATIONLOOPMODE_CONSTANT:
return quatValue;
case Animation2.ANIMATIONLOOPMODE_RELATIVE:
return quatValue.addInPlace(offsetValue.scale(repeatCount));
}
return quatValue;
case Animation2.ANIMATIONTYPE_VECTOR3:
var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
switch (loopMode) {
case Animation2.ANIMATIONLOOPMODE_CYCLE:
case Animation2.ANIMATIONLOOPMODE_CONSTANT:
return vec3Value;
case Animation2.ANIMATIONLOOPMODE_RELATIVE:
return vec3Value.add(offsetValue.scale(repeatCount));
}
case Animation2.ANIMATIONTYPE_VECTOR2:
var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
switch (loopMode) {
case Animation2.ANIMATIONLOOPMODE_CYCLE:
case Animation2.ANIMATIONLOOPMODE_CONSTANT:
return vec2Value;
case Animation2.ANIMATIONLOOPMODE_RELATIVE:
return vec2Value.add(offsetValue.scale(repeatCount));
}
case Animation2.ANIMATIONTYPE_SIZE:
switch (loopMode) {
case Animation2.ANIMATIONLOOPMODE_CYCLE:
case Animation2.ANIMATIONLOOPMODE_CONSTANT:
return this.sizeInterpolateFunction(startValue, endValue, gradient);
case Animation2.ANIMATIONLOOPMODE_RELATIVE:
return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
case Animation2.ANIMATIONTYPE_COLOR3:
switch (loopMode) {
case Animation2.ANIMATIONLOOPMODE_CYCLE:
case Animation2.ANIMATIONLOOPMODE_CONSTANT:
return this.color3InterpolateFunction(startValue, endValue, gradient);
case Animation2.ANIMATIONLOOPMODE_RELATIVE:
return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
}
case Animation2.ANIMATIONTYPE_MATRIX:
switch (loopMode) {
case Animation2.ANIMATIONLOOPMODE_CYCLE:
case Animation2.ANIMATIONLOOPMODE_CONSTANT:
if (Animation2.AllowMatricesInterpolation) {
return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
}
case Animation2.ANIMATIONLOOPMODE_RELATIVE:
return startValue;
}
default:
break;
}
break;
}
}
return this._getKeyValue(keys[keys.length - 1].value);
};
Animation2.prototype.matrixInterpolateFunction = function(startValue, endValue, gradient, result) {
if (Animation2.AllowMatrixDecomposeForInterpolation) {
if (result) {
BABYLON2.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
return result;
}
return BABYLON2.Matrix.DecomposeLerp(startValue, endValue, gradient);
}
if (result) {
BABYLON2.Matrix.LerpToRef(startValue, endValue, gradient, result);
return result;
}
return BABYLON2.Matrix.Lerp(startValue, endValue, gradient);
};
Animation2.prototype.clone = function() {
var clone = new Animation2(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
clone.enableBlending = this.enableBlending;
clone.blendingSpeed = this.blendingSpeed;
if (this._keys) {
clone.setKeys(this._keys);
}
if (this._ranges) {
clone._ranges = {};
for (var name in this._ranges) {
var range = this._ranges[name];
if (!range) {
continue;
}
clone._ranges[name] = range.clone();
}
}
return clone;
};
Animation2.prototype.setKeys = function(values) {
this._keys = values.slice(0);
};
Animation2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.property = this.targetProperty;
serializationObject.framePerSecond = this.framePerSecond;
serializationObject.dataType = this.dataType;
serializationObject.loopBehavior = this.loopMode;
serializationObject.enableBlending = this.enableBlending;
serializationObject.blendingSpeed = this.blendingSpeed;
var dataType = this.dataType;
serializationObject.keys = [];
var keys = this.getKeys();
for (var index = 0; index < keys.length; index++) {
var animationKey = keys[index];
var key = {};
key.frame = animationKey.frame;
switch (dataType) {
case Animation2.ANIMATIONTYPE_FLOAT:
key.values = [animationKey.value];
break;
case Animation2.ANIMATIONTYPE_QUATERNION:
case Animation2.ANIMATIONTYPE_MATRIX:
case Animation2.ANIMATIONTYPE_VECTOR3:
case Animation2.ANIMATIONTYPE_COLOR3:
key.values = animationKey.value.asArray();
break;
}
serializationObject.keys.push(key);
}
serializationObject.ranges = [];
for (var name in this._ranges) {
var source = this._ranges[name];
if (!source) {
continue;
}
var range = {};
range.name = name;
range.from = source.from;
range.to = source.to;
serializationObject.ranges.push(range);
}
return serializationObject;
};
Object.defineProperty(Animation2, "ANIMATIONTYPE_FLOAT", {
/**
* Get the float animation type
*/
get: function() {
return Animation2._ANIMATIONTYPE_FLOAT;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONTYPE_VECTOR3", {
/**
* Get the Vector3 animation type
*/
get: function() {
return Animation2._ANIMATIONTYPE_VECTOR3;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONTYPE_VECTOR2", {
/**
* Get the Vector2 animation type
*/
get: function() {
return Animation2._ANIMATIONTYPE_VECTOR2;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONTYPE_SIZE", {
/**
* Get the Size animation type
*/
get: function() {
return Animation2._ANIMATIONTYPE_SIZE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONTYPE_QUATERNION", {
/**
* Get the Quaternion animation type
*/
get: function() {
return Animation2._ANIMATIONTYPE_QUATERNION;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONTYPE_MATRIX", {
/**
* Get the Matrix animation type
*/
get: function() {
return Animation2._ANIMATIONTYPE_MATRIX;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONTYPE_COLOR3", {
/**
* Get the Color3 animation type
*/
get: function() {
return Animation2._ANIMATIONTYPE_COLOR3;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONLOOPMODE_RELATIVE", {
/**
* Get the Relative Loop Mode
*/
get: function() {
return Animation2._ANIMATIONLOOPMODE_RELATIVE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONLOOPMODE_CYCLE", {
/**
* Get the Cycle Loop Mode
*/
get: function() {
return Animation2._ANIMATIONLOOPMODE_CYCLE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animation2, "ANIMATIONLOOPMODE_CONSTANT", {
/**
* Get the Constant Loop Mode
*/
get: function() {
return Animation2._ANIMATIONLOOPMODE_CONSTANT;
},
enumerable: true,
configurable: true
});
Animation2._UniversalLerp = function(left, right, amount) {
var constructor = left.constructor;
if (constructor.Lerp) {
return constructor.Lerp(left, right, amount);
} else if (constructor.Slerp) {
return constructor.Slerp(left, right, amount);
} else if (left.toFixed) {
return left * (1 - amount) + amount * right;
} else {
return right;
}
};
Animation2.Parse = function(parsedAnimation) {
var animation = new Animation2(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
var dataType = parsedAnimation.dataType;
var keys = [];
var data2;
var index;
if (parsedAnimation.enableBlending) {
animation.enableBlending = parsedAnimation.enableBlending;
}
if (parsedAnimation.blendingSpeed) {
animation.blendingSpeed = parsedAnimation.blendingSpeed;
}
for (index = 0; index < parsedAnimation.keys.length; index++) {
var key = parsedAnimation.keys[index];
var inTangent;
var outTangent;
switch (dataType) {
case Animation2.ANIMATIONTYPE_FLOAT:
data2 = key.values[0];
if (key.values.length >= 1) {
inTangent = key.values[1];
}
if (key.values.length >= 2) {
outTangent = key.values[2];
}
break;
case Animation2.ANIMATIONTYPE_QUATERNION:
data2 = BABYLON2.Quaternion.FromArray(key.values);
if (key.values.length >= 8) {
var _inTangent = BABYLON2.Quaternion.FromArray(key.values.slice(4, 8));
if (!_inTangent.equals(BABYLON2.Quaternion.Zero())) {
inTangent = _inTangent;
}
}
if (key.values.length >= 12) {
var _outTangent = BABYLON2.Quaternion.FromArray(key.values.slice(8, 12));
if (!_outTangent.equals(BABYLON2.Quaternion.Zero())) {
outTangent = _outTangent;
}
}
break;
case Animation2.ANIMATIONTYPE_MATRIX:
data2 = BABYLON2.Matrix.FromArray(key.values);
break;
case Animation2.ANIMATIONTYPE_COLOR3:
data2 = BABYLON2.Color3.FromArray(key.values);
break;
case Animation2.ANIMATIONTYPE_VECTOR3:
default:
data2 = BABYLON2.Vector3.FromArray(key.values);
break;
}
var keyData = {};
keyData.frame = key.frame;
keyData.value = data2;
if (inTangent != void 0) {
keyData.inTangent = inTangent;
}
if (outTangent != void 0) {
keyData.outTangent = outTangent;
}
keys.push(keyData);
}
animation.setKeys(keys);
if (parsedAnimation.ranges) {
for (index = 0; index < parsedAnimation.ranges.length; index++) {
data2 = parsedAnimation.ranges[index];
animation.createRange(data2.name, data2.from, data2.to);
}
}
return animation;
};
Animation2.AppendSerializedAnimations = function(source, destination) {
if (source.animations) {
destination.animations = [];
for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
var animation = source.animations[animationIndex];
destination.animations.push(animation.serialize());
}
}
};
Animation2.AllowMatricesInterpolation = false;
Animation2.AllowMatrixDecomposeForInterpolation = true;
Animation2._ANIMATIONTYPE_FLOAT = 0;
Animation2._ANIMATIONTYPE_VECTOR3 = 1;
Animation2._ANIMATIONTYPE_QUATERNION = 2;
Animation2._ANIMATIONTYPE_MATRIX = 3;
Animation2._ANIMATIONTYPE_COLOR3 = 4;
Animation2._ANIMATIONTYPE_VECTOR2 = 5;
Animation2._ANIMATIONTYPE_SIZE = 6;
Animation2._ANIMATIONLOOPMODE_RELATIVE = 0;
Animation2._ANIMATIONLOOPMODE_CYCLE = 1;
Animation2._ANIMATIONLOOPMODE_CONSTANT = 2;
return Animation2;
}()
);
BABYLON2.Animation = Animation;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var TargetedAnimation = (
/** @class */
function() {
function TargetedAnimation2() {
}
return TargetedAnimation2;
}()
);
BABYLON2.TargetedAnimation = TargetedAnimation;
var AnimationGroup = (
/** @class */
function() {
function AnimationGroup2(name, scene) {
if (scene === void 0) {
scene = null;
}
this.name = name;
this._targetedAnimations = new Array();
this._animatables = new Array();
this._from = Number.MAX_VALUE;
this._to = -Number.MAX_VALUE;
this._speedRatio = 1;
this.onAnimationEndObservable = new BABYLON2.Observable();
this.onAnimationGroupEndObservable = new BABYLON2.Observable();
this.onAnimationGroupPauseObservable = new BABYLON2.Observable();
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
this._scene.animationGroups.push(this);
}
Object.defineProperty(AnimationGroup2.prototype, "from", {
/**
* Gets the first frame
*/
get: function() {
return this._from;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationGroup2.prototype, "to", {
/**
* Gets the last frame
*/
get: function() {
return this._to;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationGroup2.prototype, "isStarted", {
/**
* Define if the animations are started
*/
get: function() {
return this._isStarted;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationGroup2.prototype, "speedRatio", {
/**
* Gets or sets the speed ratio to use for all animations
*/
get: function() {
return this._speedRatio;
},
/**
* Gets or sets the speed ratio to use for all animations
*/
set: function(value) {
if (this._speedRatio === value) {
return;
}
this._speedRatio = value;
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.speedRatio = this._speedRatio;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationGroup2.prototype, "targetedAnimations", {
/**
* Gets the targeted animations for this animation group
*/
get: function() {
return this._targetedAnimations;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationGroup2.prototype, "animatables", {
/**
* returning the list of animatables controlled by this animation group.
*/
get: function() {
return this._animatables;
},
enumerable: true,
configurable: true
});
AnimationGroup2.prototype.addTargetedAnimation = function(animation, target) {
var targetedAnimation = {
animation,
target
};
var keys = animation.getKeys();
if (this._from > keys[0].frame) {
this._from = keys[0].frame;
}
if (this._to < keys[keys.length - 1].frame) {
this._to = keys[keys.length - 1].frame;
}
this._targetedAnimations.push(targetedAnimation);
return targetedAnimation;
};
AnimationGroup2.prototype.normalize = function(beginFrame, endFrame) {
if (beginFrame === void 0) {
beginFrame = null;
}
if (endFrame === void 0) {
endFrame = null;
}
if (beginFrame == null) {
beginFrame = this._from;
}
if (endFrame == null) {
endFrame = this._to;
}
for (var index = 0; index < this._targetedAnimations.length; index++) {
var targetedAnimation = this._targetedAnimations[index];
var keys = targetedAnimation.animation.getKeys();
var startKey = keys[0];
var endKey = keys[keys.length - 1];
if (startKey.frame > beginFrame) {
var newKey = {
frame: beginFrame,
value: startKey.value,
inTangent: startKey.inTangent,
outTangent: startKey.outTangent,
interpolation: startKey.interpolation
};
keys.splice(0, 0, newKey);
}
if (endKey.frame < endFrame) {
var newKey = {
frame: endFrame,
value: endKey.value,
inTangent: endKey.outTangent,
outTangent: endKey.outTangent,
interpolation: endKey.interpolation
};
keys.push(newKey);
}
}
this._from = beginFrame;
this._to = endFrame;
return this;
};
AnimationGroup2.prototype.start = function(loop, speedRatio, from, to) {
var _this = this;
if (loop === void 0) {
loop = false;
}
if (speedRatio === void 0) {
speedRatio = 1;
}
if (this._isStarted || this._targetedAnimations.length === 0) {
return this;
}
var _loop_1 = function(targetedAnimation2) {
var animatable = this_1._scene.beginDirectAnimation(targetedAnimation2.target, [targetedAnimation2.animation], from !== void 0 ? from : this_1._from, to !== void 0 ? to : this_1._to, loop, speedRatio);
animatable.onAnimationEnd = function() {
_this.onAnimationEndObservable.notifyObservers(targetedAnimation2);
_this._checkAnimationGroupEnded(animatable);
};
this_1._animatables.push(animatable);
};
var this_1 = this;
for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
var targetedAnimation = _a[_i];
_loop_1(targetedAnimation);
}
this._speedRatio = speedRatio;
this._isStarted = true;
return this;
};
AnimationGroup2.prototype.pause = function() {
if (!this._isStarted) {
return this;
}
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.pause();
}
this.onAnimationGroupPauseObservable.notifyObservers(this);
return this;
};
AnimationGroup2.prototype.play = function(loop) {
if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
if (loop !== void 0) {
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.loopAnimation = loop;
}
}
this.restart();
} else {
this.stop();
this.start(loop, this._speedRatio);
}
return this;
};
AnimationGroup2.prototype.reset = function() {
if (!this._isStarted) {
return this;
}
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.reset();
}
return this;
};
AnimationGroup2.prototype.restart = function() {
if (!this._isStarted) {
return this;
}
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.restart();
}
return this;
};
AnimationGroup2.prototype.stop = function() {
if (!this._isStarted) {
return this;
}
var list = this._animatables.slice();
for (var index = 0; index < list.length; index++) {
list[index].stop();
}
this._isStarted = false;
return this;
};
AnimationGroup2.prototype.setWeightForAllAnimatables = function(weight) {
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.weight = weight;
}
return this;
};
AnimationGroup2.prototype.syncAllAnimationsWith = function(root) {
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.syncWith(root);
}
return this;
};
AnimationGroup2.prototype.goToFrame = function(frame) {
if (!this._isStarted) {
return this;
}
for (var index = 0; index < this._animatables.length; index++) {
var animatable = this._animatables[index];
animatable.goToFrame(frame);
}
return this;
};
AnimationGroup2.prototype.dispose = function() {
this._targetedAnimations = [];
this._animatables = [];
var index = this._scene.animationGroups.indexOf(this);
if (index > -1) {
this._scene.animationGroups.splice(index, 1);
}
};
AnimationGroup2.prototype._checkAnimationGroupEnded = function(animatable) {
var idx = this._animatables.indexOf(animatable);
if (idx > -1) {
this._animatables.splice(idx, 1);
}
if (this._animatables.length === 0) {
this._isStarted = false;
this.onAnimationGroupEndObservable.notifyObservers(this);
}
};
AnimationGroup2.Parse = function(parsedAnimationGroup, scene) {
var animationGroup = new BABYLON2.AnimationGroup(parsedAnimationGroup.name, scene);
for (var i2 = 0; i2 < parsedAnimationGroup.targetedAnimations.length; i2++) {
var targetedAnimation = parsedAnimationGroup.targetedAnimations[i2];
var animation = BABYLON2.Animation.Parse(targetedAnimation.animation);
var id = targetedAnimation.targetId;
var targetNode = scene.getNodeByID(id);
if (targetNode != null) {
animationGroup.addTargetedAnimation(animation, targetNode);
}
}
if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
}
return animationGroup;
};
AnimationGroup2.prototype.getClassName = function() {
return "AnimationGroup";
};
AnimationGroup2.prototype.toString = function(fullDetails) {
var ret = "Name: " + this.name;
ret += ", type: " + this.getClassName();
if (fullDetails) {
ret += ", from: " + this._from;
ret += ", to: " + this._to;
ret += ", isStarted: " + this._isStarted;
ret += ", speedRatio: " + this._speedRatio;
ret += ", targetedAnimations length: " + this._targetedAnimations.length;
ret += ", animatables length: " + this._animatables;
}
return ret;
};
return AnimationGroup2;
}()
);
BABYLON2.AnimationGroup = AnimationGroup;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _staticOffsetValueQuaternion = Object.freeze(new BABYLON2.Quaternion(0, 0, 0, 0));
var _staticOffsetValueVector3 = Object.freeze(BABYLON2.Vector3.Zero());
var _staticOffsetValueVector2 = Object.freeze(BABYLON2.Vector2.Zero());
var _staticOffsetValueSize = Object.freeze(BABYLON2.Size.Zero());
var _staticOffsetValueColor3 = Object.freeze(BABYLON2.Color3.Black());
var RuntimeAnimation = (
/** @class */
function() {
function RuntimeAnimation2(target, animation, scene, host) {
var _this = this;
this._events = new Array();
this._currentFrame = 0;
this._originalValue = new Array();
this._offsetsCache = {};
this._highLimitsCache = {};
this._stopped = false;
this._blendingFactor = 0;
this._targetPath = "";
this._weight = 1;
this._ratioOffset = 0;
this._previousDelay = 0;
this._previousRatio = 0;
this._animation = animation;
this._target = target;
this._scene = scene;
this._host = host;
animation._runtimeAnimations.push(this);
var events = animation.getEvents();
if (events && events.length > 0) {
events.forEach(function(e2) {
_this._events.push(e2._clone());
});
}
}
Object.defineProperty(RuntimeAnimation2.prototype, "currentFrame", {
/**
* Gets the current frame of the runtime animation
*/
get: function() {
return this._currentFrame;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeAnimation2.prototype, "weight", {
/**
* Gets the weight of the runtime animation
*/
get: function() {
return this._weight;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeAnimation2.prototype, "currentValue", {
/**
* Gets the current value of the runtime animation
*/
get: function() {
return this._currentValue;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeAnimation2.prototype, "targetPath", {
/**
* Gets the target path of the runtime animation
*/
get: function() {
return this._targetPath;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeAnimation2.prototype, "target", {
/**
* Gets the actual target of the runtime animation
*/
get: function() {
return this._activeTarget;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeAnimation2.prototype, "animation", {
/**
* Gets the animation from the runtime animation
*/
get: function() {
return this._animation;
},
enumerable: true,
configurable: true
});
RuntimeAnimation2.prototype.reset = function(restoreOriginal) {
if (restoreOriginal === void 0) {
restoreOriginal = false;
}
if (restoreOriginal) {
if (this._target instanceof Array) {
var index = 0;
for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
var target = _a[_i];
if (this._originalValue[index] !== void 0) {
this._setValue(target, this._originalValue[index], -1);
}
index++;
}
} else {
if (this._originalValue[0] !== void 0) {
this._setValue(this._target, this._originalValue[0], -1);
}
}
}
this._offsetsCache = {};
this._highLimitsCache = {};
this._currentFrame = 0;
this._blendingFactor = 0;
this._originalValue = new Array();
for (var index = 0; index < this._events.length; index++) {
this._events[index].isDone = false;
}
};
RuntimeAnimation2.prototype.isStopped = function() {
return this._stopped;
};
RuntimeAnimation2.prototype.dispose = function() {
var index = this._animation.runtimeAnimations.indexOf(this);
if (index > -1) {
this._animation.runtimeAnimations.splice(index, 1);
}
};
RuntimeAnimation2.prototype._interpolate = function(currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
this._currentFrame = currentFrame;
if (this._animation.dataType === BABYLON2.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
this._workValue = BABYLON2.Matrix.Zero();
}
return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
};
RuntimeAnimation2.prototype.setValue = function(currentValue, weight) {
if (weight === void 0) {
weight = 1;
}
if (this._target instanceof Array) {
var index = 0;
for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
var target = _a[_i];
this._setValue(target, currentValue, weight, index);
index++;
}
} else {
this._setValue(this._target, currentValue, weight);
}
};
RuntimeAnimation2.prototype._setValue = function(target, currentValue, weight, targetIndex) {
if (targetIndex === void 0) {
targetIndex = 0;
}
var path;
var destination;
var targetPropertyPath = this._animation.targetPropertyPath;
if (targetPropertyPath.length > 1) {
var property = target[targetPropertyPath[0]];
for (var index = 1; index < targetPropertyPath.length - 1; index++) {
property = property[targetPropertyPath[index]];
}
path = targetPropertyPath[targetPropertyPath.length - 1];
destination = property;
} else {
path = targetPropertyPath[0];
destination = target;
}
this._targetPath = path;
this._activeTarget = destination;
this._weight = weight;
if (this._originalValue[targetIndex] === void 0) {
var originalValue = void 0;
if (destination.getRestPose && path === "_matrix") {
originalValue = destination.getRestPose();
} else {
originalValue = destination[path];
}
if (originalValue && originalValue.clone) {
this._originalValue[targetIndex] = originalValue.clone();
} else {
this._originalValue[targetIndex] = originalValue;
}
}
var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
if (enableBlending && this._blendingFactor <= 1) {
if (!this._originalBlendValue) {
var originalValue = destination[path];
if (originalValue.clone) {
this._originalBlendValue = originalValue.clone();
} else {
this._originalBlendValue = originalValue;
}
}
if (this._originalBlendValue.m) {
if (BABYLON2.Animation.AllowMatrixDecomposeForInterpolation) {
if (this._currentValue) {
BABYLON2.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
} else {
this._currentValue = BABYLON2.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
}
} else {
if (this._currentValue) {
BABYLON2.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
} else {
this._currentValue = BABYLON2.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
}
}
} else {
this._currentValue = BABYLON2.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
}
var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
this._blendingFactor += blendingSpeed;
} else {
this._currentValue = currentValue;
}
if (weight !== -1) {
this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
} else {
destination[path] = this._currentValue;
}
if (target.markAsDirty) {
target.markAsDirty(this._animation.targetProperty);
}
};
RuntimeAnimation2.prototype._getCorrectLoopMode = function() {
if (this._target && this._target.animationPropertiesOverride) {
return this._target.animationPropertiesOverride.loopMode;
}
return this._animation.loopMode;
};
RuntimeAnimation2.prototype.goToFrame = function(frame) {
var keys = this._animation.getKeys();
if (frame < keys[0].frame) {
frame = keys[0].frame;
} else if (frame > keys[keys.length - 1].frame) {
frame = keys[keys.length - 1].frame;
}
var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
this.setValue(currentValue, -1);
};
RuntimeAnimation2.prototype._prepareForSpeedRatioChange = function(newSpeedRatio) {
var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1e3;
this._ratioOffset = this._previousRatio - newRatio;
};
RuntimeAnimation2.prototype.animate = function(delay, from, to, loop, speedRatio, weight) {
if (weight === void 0) {
weight = -1;
}
var targetPropertyPath = this._animation.targetPropertyPath;
if (!targetPropertyPath || targetPropertyPath.length < 1) {
this._stopped = true;
return false;
}
var returnValue = true;
var keys = this._animation.getKeys();
if (keys[0].frame !== 0) {
var newKey = { frame: 0, value: keys[0].value };
keys.splice(0, 0, newKey);
} else if (keys.length === 1) {
var newKey = { frame: 1e-3, value: keys[0].value };
keys.push(newKey);
}
if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
from = keys[0].frame;
}
if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
to = keys[keys.length - 1].frame;
}
if (from === to) {
if (from > keys[0].frame) {
from--;
} else if (to < keys[keys.length - 1].frame) {
to++;
}
}
var range = to - from;
var offsetValue;
var ratio = delay * (this._animation.framePerSecond * speedRatio) / 1e3 + this._ratioOffset;
var highLimitValue = 0;
this._previousDelay = delay;
this._previousRatio = ratio;
if ((to > from && ratio >= range || from > to && ratio <= range) && !loop) {
returnValue = false;
highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
} else {
if (this._getCorrectLoopMode() !== BABYLON2.Animation.ANIMATIONLOOPMODE_CYCLE) {
var keyOffset = to.toString() + from.toString();
if (!this._offsetsCache[keyOffset]) {
var fromValue = this._interpolate(from, 0, BABYLON2.Animation.ANIMATIONLOOPMODE_CYCLE);
var toValue = this._interpolate(to, 0, BABYLON2.Animation.ANIMATIONLOOPMODE_CYCLE);
switch (this._animation.dataType) {
case BABYLON2.Animation.ANIMATIONTYPE_FLOAT:
this._offsetsCache[keyOffset] = toValue - fromValue;
break;
case BABYLON2.Animation.ANIMATIONTYPE_QUATERNION:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
break;
case BABYLON2.Animation.ANIMATIONTYPE_VECTOR3:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
case BABYLON2.Animation.ANIMATIONTYPE_VECTOR2:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
case BABYLON2.Animation.ANIMATIONTYPE_SIZE:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
case BABYLON2.Animation.ANIMATIONTYPE_COLOR3:
this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
default:
break;
}
this._highLimitsCache[keyOffset] = toValue;
}
highLimitValue = this._highLimitsCache[keyOffset];
offsetValue = this._offsetsCache[keyOffset];
}
}
if (offsetValue === void 0) {
switch (this._animation.dataType) {
case BABYLON2.Animation.ANIMATIONTYPE_FLOAT:
offsetValue = 0;
break;
case BABYLON2.Animation.ANIMATIONTYPE_QUATERNION:
offsetValue = _staticOffsetValueQuaternion;
break;
case BABYLON2.Animation.ANIMATIONTYPE_VECTOR3:
offsetValue = _staticOffsetValueVector3;
break;
case BABYLON2.Animation.ANIMATIONTYPE_VECTOR2:
offsetValue = _staticOffsetValueVector2;
break;
case BABYLON2.Animation.ANIMATIONTYPE_SIZE:
offsetValue = _staticOffsetValueSize;
break;
case BABYLON2.Animation.ANIMATIONTYPE_COLOR3:
offsetValue = _staticOffsetValueColor3;
}
}
var repeatCount = ratio / range >> 0;
var currentFrame = returnValue ? from + ratio % range : to;
if (this._host && this._host.syncRoot) {
var syncRoot = this._host.syncRoot;
var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
currentFrame = from + (to - from) * hostNormalizedFrame;
}
var events = this._events;
if (range > 0 && this.currentFrame > currentFrame || range < 0 && this.currentFrame < currentFrame) {
for (var index = 0; index < events.length; index++) {
if (!events[index].onlyOnce) {
events[index].isDone = false;
}
}
}
var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
this.setValue(currentValue, weight);
for (var index = 0; index < events.length; index++) {
if (range > 0 && currentFrame >= events[index].frame && events[index].frame >= from || range < 0 && currentFrame <= events[index].frame && events[index].frame <= from) {
var event = events[index];
if (!event.isDone) {
if (event.onlyOnce) {
events.splice(index, 1);
index--;
}
event.isDone = true;
event.action(currentFrame);
}
}
}
if (!returnValue) {
this._stopped = true;
}
return returnValue;
};
return RuntimeAnimation2;
}()
);
BABYLON2.RuntimeAnimation = RuntimeAnimation;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Animatable = (
/** @class */
function() {
function Animatable2(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
if (fromFrame === void 0) {
fromFrame = 0;
}
if (toFrame === void 0) {
toFrame = 100;
}
if (loopAnimation === void 0) {
loopAnimation = false;
}
if (speedRatio === void 0) {
speedRatio = 1;
}
this.target = target;
this.fromFrame = fromFrame;
this.toFrame = toFrame;
this.loopAnimation = loopAnimation;
this.onAnimationEnd = onAnimationEnd;
this._localDelayOffset = null;
this._pausedDelay = null;
this._runtimeAnimations = new Array();
this._paused = false;
this._speedRatio = 1;
this._weight = -1;
this.disposeOnEnd = true;
this.animationStarted = false;
this.onAnimationEndObservable = new BABYLON2.Observable();
this._scene = scene;
if (animations) {
this.appendAnimations(target, animations);
}
this._speedRatio = speedRatio;
scene._activeAnimatables.push(this);
}
Object.defineProperty(Animatable2.prototype, "syncRoot", {
/**
* Gets the root Animatable used to synchronize and normalize animations
*/
get: function() {
return this._syncRoot;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animatable2.prototype, "masterFrame", {
/**
* Gets the current frame of the first RuntimeAnimation
* Used to synchronize Animatables
*/
get: function() {
if (this._runtimeAnimations.length === 0) {
return 0;
}
return this._runtimeAnimations[0].currentFrame;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animatable2.prototype, "weight", {
/**
* Gets or sets the animatable weight (-1.0 by default meaning not weighted)
*/
get: function() {
return this._weight;
},
set: function(value) {
if (value === -1) {
this._weight = -1;
return;
}
this._weight = Math.min(Math.max(value, 0), 1);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Animatable2.prototype, "speedRatio", {
/**
* Gets or sets the speed ratio to apply to the animatable (1.0 by default)
*/
get: function() {
return this._speedRatio;
},
set: function(value) {
for (var index = 0; index < this._runtimeAnimations.length; index++) {
var animation = this._runtimeAnimations[index];
animation._prepareForSpeedRatioChange(value);
}
this._speedRatio = value;
},
enumerable: true,
configurable: true
});
Animatable2.prototype.syncWith = function(root) {
this._syncRoot = root;
if (root) {
var index = this._scene._activeAnimatables.indexOf(this);
if (index > -1) {
this._scene._activeAnimatables.splice(index, 1);
this._scene._activeAnimatables.push(this);
}
}
return this;
};
Animatable2.prototype.getAnimations = function() {
return this._runtimeAnimations;
};
Animatable2.prototype.appendAnimations = function(target, animations) {
for (var index = 0; index < animations.length; index++) {
var animation = animations[index];
this._runtimeAnimations.push(new BABYLON2.RuntimeAnimation(target, animation, this._scene, this));
}
};
Animatable2.prototype.getAnimationByTargetProperty = function(property) {
var runtimeAnimations = this._runtimeAnimations;
for (var index = 0; index < runtimeAnimations.length; index++) {
if (runtimeAnimations[index].animation.targetProperty === property) {
return runtimeAnimations[index].animation;
}
}
return null;
};
Animatable2.prototype.getRuntimeAnimationByTargetProperty = function(property) {
var runtimeAnimations = this._runtimeAnimations;
for (var index = 0; index < runtimeAnimations.length; index++) {
if (runtimeAnimations[index].animation.targetProperty === property) {
return runtimeAnimations[index];
}
}
return null;
};
Animatable2.prototype.reset = function() {
var runtimeAnimations = this._runtimeAnimations;
for (var index = 0; index < runtimeAnimations.length; index++) {
runtimeAnimations[index].reset(true);
}
this._localDelayOffset = null;
this._pausedDelay = null;
};
Animatable2.prototype.enableBlending = function(blendingSpeed) {
var runtimeAnimations = this._runtimeAnimations;
for (var index = 0; index < runtimeAnimations.length; index++) {
runtimeAnimations[index].animation.enableBlending = true;
runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
}
};
Animatable2.prototype.disableBlending = function() {
var runtimeAnimations = this._runtimeAnimations;
for (var index = 0; index < runtimeAnimations.length; index++) {
runtimeAnimations[index].animation.enableBlending = false;
}
};
Animatable2.prototype.goToFrame = function(frame) {
var runtimeAnimations = this._runtimeAnimations;
if (runtimeAnimations[0]) {
var fps = runtimeAnimations[0].animation.framePerSecond;
var currentFrame = runtimeAnimations[0].currentFrame;
var adjustTime = frame - currentFrame;
var delay = adjustTime * 1e3 / (fps * this.speedRatio);
if (this._localDelayOffset === null) {
this._localDelayOffset = 0;
}
this._localDelayOffset -= delay;
}
for (var index = 0; index < runtimeAnimations.length; index++) {
runtimeAnimations[index].goToFrame(frame);
}
};
Animatable2.prototype.pause = function() {
if (this._paused) {
return;
}
this._paused = true;
};
Animatable2.prototype.restart = function() {
this._paused = false;
};
Animatable2.prototype._raiseOnAnimationEnd = function() {
if (this.onAnimationEnd) {
this.onAnimationEnd();
}
this.onAnimationEndObservable.notifyObservers(this);
};
Animatable2.prototype.stop = function(animationName, targetMask) {
if (animationName || targetMask) {
var idx = this._scene._activeAnimatables.indexOf(this);
if (idx > -1) {
var runtimeAnimations = this._runtimeAnimations;
for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
var runtimeAnimation = runtimeAnimations[index];
if (animationName && runtimeAnimation.animation.name != animationName) {
continue;
}
if (targetMask && !targetMask(runtimeAnimation.target)) {
continue;
}
runtimeAnimation.dispose();
runtimeAnimations.splice(index, 1);
}
if (runtimeAnimations.length == 0) {
this._scene._activeAnimatables.splice(idx, 1);
this._raiseOnAnimationEnd();
}
}
} else {
var index = this._scene._activeAnimatables.indexOf(this);
if (index > -1) {
this._scene._activeAnimatables.splice(index, 1);
var runtimeAnimations = this._runtimeAnimations;
for (var index = 0; index < runtimeAnimations.length; index++) {
runtimeAnimations[index].dispose();
}
this._raiseOnAnimationEnd();
}
}
};
Animatable2.prototype.waitAsync = function() {
var _this = this;
return new Promise(function(resolve, reject) {
_this.onAnimationEndObservable.add(function() {
resolve(_this);
}, void 0, void 0, _this, true);
});
};
Animatable2.prototype._animate = function(delay) {
if (this._paused) {
this.animationStarted = false;
if (this._pausedDelay === null) {
this._pausedDelay = delay;
}
return true;
}
if (this._localDelayOffset === null) {
this._localDelayOffset = delay;
this._pausedDelay = null;
} else if (this._pausedDelay !== null) {
this._localDelayOffset += delay - this._pausedDelay;
this._pausedDelay = null;
}
if (this._weight === 0) {
return true;
}
var running = false;
var runtimeAnimations = this._runtimeAnimations;
var index;
for (index = 0; index < runtimeAnimations.length; index++) {
var animation = runtimeAnimations[index];
var isRunning2 = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
running = running || isRunning2;
}
this.animationStarted = running;
if (!running) {
if (this.disposeOnEnd) {
index = this._scene._activeAnimatables.indexOf(this);
this._scene._activeAnimatables.splice(index, 1);
for (index = 0; index < runtimeAnimations.length; index++) {
runtimeAnimations[index].dispose();
}
}
this._raiseOnAnimationEnd();
if (this.disposeOnEnd) {
this.onAnimationEnd = null;
this.onAnimationEndObservable.clear();
}
}
return running;
};
return Animatable2;
}()
);
BABYLON2.Animatable = Animatable;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var EasingFunction = (
/** @class */
function() {
function EasingFunction2() {
this._easingMode = EasingFunction2.EASINGMODE_EASEIN;
}
EasingFunction2.prototype.setEasingMode = function(easingMode) {
var n = Math.min(Math.max(easingMode, 0), 2);
this._easingMode = n;
};
EasingFunction2.prototype.getEasingMode = function() {
return this._easingMode;
};
EasingFunction2.prototype.easeInCore = function(gradient) {
throw new Error("You must implement this method");
};
EasingFunction2.prototype.ease = function(gradient) {
switch (this._easingMode) {
case EasingFunction2.EASINGMODE_EASEIN:
return this.easeInCore(gradient);
case EasingFunction2.EASINGMODE_EASEOUT:
return 1 - this.easeInCore(1 - gradient);
}
if (gradient >= 0.5) {
return (1 - this.easeInCore((1 - gradient) * 2)) * 0.5 + 0.5;
}
return this.easeInCore(gradient * 2) * 0.5;
};
EasingFunction2.EASINGMODE_EASEIN = 0;
EasingFunction2.EASINGMODE_EASEOUT = 1;
EasingFunction2.EASINGMODE_EASEINOUT = 2;
return EasingFunction2;
}()
);
BABYLON2.EasingFunction = EasingFunction;
var CircleEase = (
/** @class */
function(_super) {
__extends(CircleEase2, _super);
function CircleEase2() {
return _super !== null && _super.apply(this, arguments) || this;
}
CircleEase2.prototype.easeInCore = function(gradient) {
gradient = Math.max(0, Math.min(1, gradient));
return 1 - Math.sqrt(1 - gradient * gradient);
};
return CircleEase2;
}(EasingFunction)
);
BABYLON2.CircleEase = CircleEase;
var BackEase = (
/** @class */
function(_super) {
__extends(BackEase2, _super);
function BackEase2(amplitude) {
if (amplitude === void 0) {
amplitude = 1;
}
var _this = _super.call(this) || this;
_this.amplitude = amplitude;
return _this;
}
BackEase2.prototype.easeInCore = function(gradient) {
var num = Math.max(0, this.amplitude);
return Math.pow(gradient, 3) - gradient * num * Math.sin(3.141592653589793 * gradient);
};
return BackEase2;
}(EasingFunction)
);
BABYLON2.BackEase = BackEase;
var BounceEase = (
/** @class */
function(_super) {
__extends(BounceEase2, _super);
function BounceEase2(bounces, bounciness) {
if (bounces === void 0) {
bounces = 3;
}
if (bounciness === void 0) {
bounciness = 2;
}
var _this = _super.call(this) || this;
_this.bounces = bounces;
_this.bounciness = bounciness;
return _this;
}
BounceEase2.prototype.easeInCore = function(gradient) {
var y = Math.max(0, this.bounces);
var bounciness = this.bounciness;
if (bounciness <= 1) {
bounciness = 1.001;
}
var num9 = Math.pow(bounciness, y);
var num5 = 1 - bounciness;
var num4 = (1 - num9) / num5 + num9 * 0.5;
var num15 = gradient * num4;
var num65 = Math.log(-num15 * (1 - bounciness) + 1) / Math.log(bounciness);
var num3 = Math.floor(num65);
var num13 = num3 + 1;
var num8 = (1 - Math.pow(bounciness, num3)) / (num5 * num4);
var num12 = (1 - Math.pow(bounciness, num13)) / (num5 * num4);
var num7 = (num8 + num12) * 0.5;
var num6 = gradient - num7;
var num2 = num7 - num8;
return -Math.pow(1 / bounciness, y - num3) / (num2 * num2) * (num6 - num2) * (num6 + num2);
};
return BounceEase2;
}(EasingFunction)
);
BABYLON2.BounceEase = BounceEase;
var CubicEase = (
/** @class */
function(_super) {
__extends(CubicEase2, _super);
function CubicEase2() {
return _super !== null && _super.apply(this, arguments) || this;
}
CubicEase2.prototype.easeInCore = function(gradient) {
return gradient * gradient * gradient;
};
return CubicEase2;
}(EasingFunction)
);
BABYLON2.CubicEase = CubicEase;
var ElasticEase = (
/** @class */
function(_super) {
__extends(ElasticEase2, _super);
function ElasticEase2(oscillations, springiness) {
if (oscillations === void 0) {
oscillations = 3;
}
if (springiness === void 0) {
springiness = 3;
}
var _this = _super.call(this) || this;
_this.oscillations = oscillations;
_this.springiness = springiness;
return _this;
}
ElasticEase2.prototype.easeInCore = function(gradient) {
var num2;
var num3 = Math.max(0, this.oscillations);
var num = Math.max(0, this.springiness);
if (num == 0) {
num2 = gradient;
} else {
num2 = (Math.exp(num * gradient) - 1) / (Math.exp(num) - 1);
}
return num2 * Math.sin((6.283185307179586 * num3 + 1.5707963267948966) * gradient);
};
return ElasticEase2;
}(EasingFunction)
);
BABYLON2.ElasticEase = ElasticEase;
var ExponentialEase = (
/** @class */
function(_super) {
__extends(ExponentialEase2, _super);
function ExponentialEase2(exponent) {
if (exponent === void 0) {
exponent = 2;
}
var _this = _super.call(this) || this;
_this.exponent = exponent;
return _this;
}
ExponentialEase2.prototype.easeInCore = function(gradient) {
if (this.exponent <= 0) {
return gradient;
}
return (Math.exp(this.exponent * gradient) - 1) / (Math.exp(this.exponent) - 1);
};
return ExponentialEase2;
}(EasingFunction)
);
BABYLON2.ExponentialEase = ExponentialEase;
var PowerEase = (
/** @class */
function(_super) {
__extends(PowerEase2, _super);
function PowerEase2(power) {
if (power === void 0) {
power = 2;
}
var _this = _super.call(this) || this;
_this.power = power;
return _this;
}
PowerEase2.prototype.easeInCore = function(gradient) {
var y = Math.max(0, this.power);
return Math.pow(gradient, y);
};
return PowerEase2;
}(EasingFunction)
);
BABYLON2.PowerEase = PowerEase;
var QuadraticEase = (
/** @class */
function(_super) {
__extends(QuadraticEase2, _super);
function QuadraticEase2() {
return _super !== null && _super.apply(this, arguments) || this;
}
QuadraticEase2.prototype.easeInCore = function(gradient) {
return gradient * gradient;
};
return QuadraticEase2;
}(EasingFunction)
);
BABYLON2.QuadraticEase = QuadraticEase;
var QuarticEase = (
/** @class */
function(_super) {
__extends(QuarticEase2, _super);
function QuarticEase2() {
return _super !== null && _super.apply(this, arguments) || this;
}
QuarticEase2.prototype.easeInCore = function(gradient) {
return gradient * gradient * gradient * gradient;
};
return QuarticEase2;
}(EasingFunction)
);
BABYLON2.QuarticEase = QuarticEase;
var QuinticEase = (
/** @class */
function(_super) {
__extends(QuinticEase2, _super);
function QuinticEase2() {
return _super !== null && _super.apply(this, arguments) || this;
}
QuinticEase2.prototype.easeInCore = function(gradient) {
return gradient * gradient * gradient * gradient * gradient;
};
return QuinticEase2;
}(EasingFunction)
);
BABYLON2.QuinticEase = QuinticEase;
var SineEase = (
/** @class */
function(_super) {
__extends(SineEase2, _super);
function SineEase2() {
return _super !== null && _super.apply(this, arguments) || this;
}
SineEase2.prototype.easeInCore = function(gradient) {
return 1 - Math.sin(1.5707963267948966 * (1 - gradient));
};
return SineEase2;
}(EasingFunction)
);
BABYLON2.SineEase = SineEase;
var BezierCurveEase = (
/** @class */
function(_super) {
__extends(BezierCurveEase2, _super);
function BezierCurveEase2(x1, y1, x2, y2) {
if (x1 === void 0) {
x1 = 0;
}
if (y1 === void 0) {
y1 = 0;
}
if (x2 === void 0) {
x2 = 1;
}
if (y2 === void 0) {
y2 = 1;
}
var _this = _super.call(this) || this;
_this.x1 = x1;
_this.y1 = y1;
_this.x2 = x2;
_this.y2 = y2;
return _this;
}
BezierCurveEase2.prototype.easeInCore = function(gradient) {
return BABYLON2.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
};
return BezierCurveEase2;
}(EasingFunction)
);
BABYLON2.BezierCurveEase = BezierCurveEase;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Condition = (
/** @class */
function() {
function Condition2(actionManager) {
this._actionManager = actionManager;
}
Condition2.prototype.isValid = function() {
return true;
};
Condition2.prototype._getProperty = function(propertyPath) {
return this._actionManager._getProperty(propertyPath);
};
Condition2.prototype._getEffectiveTarget = function(target, propertyPath) {
return this._actionManager._getEffectiveTarget(target, propertyPath);
};
Condition2.prototype.serialize = function() {
};
Condition2.prototype._serialize = function(serializedCondition) {
return {
type: 2,
children: [],
name: serializedCondition.name,
properties: serializedCondition.properties
};
};
return Condition2;
}()
);
BABYLON2.Condition = Condition;
var ValueCondition = (
/** @class */
function(_super) {
__extends(ValueCondition2, _super);
function ValueCondition2(actionManager, target, propertyPath, value, operator) {
if (operator === void 0) {
operator = ValueCondition2.IsEqual;
}
var _this = _super.call(this, actionManager) || this;
_this.propertyPath = propertyPath;
_this.value = value;
_this.operator = operator;
_this._target = target;
_this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
_this._property = _this._getProperty(_this.propertyPath);
return _this;
}
Object.defineProperty(ValueCondition2, "IsEqual", {
/**
* returns the number for IsEqual
*/
get: function() {
return ValueCondition2._IsEqual;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ValueCondition2, "IsDifferent", {
/**
* Returns the number for IsDifferent
*/
get: function() {
return ValueCondition2._IsDifferent;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ValueCondition2, "IsGreater", {
/**
* Returns the number for IsGreater
*/
get: function() {
return ValueCondition2._IsGreater;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ValueCondition2, "IsLesser", {
/**
* Returns the number for IsLesser
*/
get: function() {
return ValueCondition2._IsLesser;
},
enumerable: true,
configurable: true
});
ValueCondition2.prototype.isValid = function() {
switch (this.operator) {
case ValueCondition2.IsGreater:
return this._effectiveTarget[this._property] > this.value;
case ValueCondition2.IsLesser:
return this._effectiveTarget[this._property] < this.value;
case ValueCondition2.IsEqual:
case ValueCondition2.IsDifferent:
var check;
if (this.value.equals) {
check = this.value.equals(this._effectiveTarget[this._property]);
} else {
check = this.value === this._effectiveTarget[this._property];
}
return this.operator === ValueCondition2.IsEqual ? check : !check;
}
return false;
};
ValueCondition2.prototype.serialize = function() {
return this._serialize({
name: "ValueCondition",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "propertyPath", value: this.propertyPath },
{ name: "value", value: BABYLON2.Action._SerializeValueAsString(this.value) },
{ name: "operator", value: ValueCondition2.GetOperatorName(this.operator) }
]
});
};
ValueCondition2.GetOperatorName = function(operator) {
switch (operator) {
case ValueCondition2._IsEqual:
return "IsEqual";
case ValueCondition2._IsDifferent:
return "IsDifferent";
case ValueCondition2._IsGreater:
return "IsGreater";
case ValueCondition2._IsLesser:
return "IsLesser";
default:
return "";
}
};
ValueCondition2._IsEqual = 0;
ValueCondition2._IsDifferent = 1;
ValueCondition2._IsGreater = 2;
ValueCondition2._IsLesser = 3;
return ValueCondition2;
}(Condition)
);
BABYLON2.ValueCondition = ValueCondition;
var PredicateCondition = (
/** @class */
function(_super) {
__extends(PredicateCondition2, _super);
function PredicateCondition2(actionManager, predicate) {
var _this = _super.call(this, actionManager) || this;
_this.predicate = predicate;
return _this;
}
PredicateCondition2.prototype.isValid = function() {
return this.predicate();
};
return PredicateCondition2;
}(Condition)
);
BABYLON2.PredicateCondition = PredicateCondition;
var StateCondition = (
/** @class */
function(_super) {
__extends(StateCondition2, _super);
function StateCondition2(actionManager, target, value) {
var _this = _super.call(this, actionManager) || this;
_this.value = value;
_this._target = target;
return _this;
}
StateCondition2.prototype.isValid = function() {
return this._target.state === this.value;
};
StateCondition2.prototype.serialize = function() {
return this._serialize({
name: "StateCondition",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "value", value: this.value }
]
});
};
return StateCondition2;
}(Condition)
);
BABYLON2.StateCondition = StateCondition;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Action = (
/** @class */
function() {
function Action2(triggerOptions, condition) {
this.triggerOptions = triggerOptions;
this.onBeforeExecuteObservable = new BABYLON2.Observable();
if (triggerOptions.parameter) {
this.trigger = triggerOptions.trigger;
this._triggerParameter = triggerOptions.parameter;
} else if (triggerOptions.trigger) {
this.trigger = triggerOptions.trigger;
} else {
this.trigger = triggerOptions;
}
this._nextActiveAction = this;
this._condition = condition;
}
Action2.prototype._prepare = function() {
};
Action2.prototype.getTriggerParameter = function() {
return this._triggerParameter;
};
Action2.prototype._executeCurrent = function(evt) {
if (this._nextActiveAction._condition) {
var condition = this._nextActiveAction._condition;
var currentRenderId = this._actionManager.getScene().getRenderId();
if (condition._evaluationId === currentRenderId) {
if (!condition._currentResult) {
return;
}
} else {
condition._evaluationId = currentRenderId;
if (!condition.isValid()) {
condition._currentResult = false;
return;
}
condition._currentResult = true;
}
}
this.onBeforeExecuteObservable.notifyObservers(this);
this._nextActiveAction.execute(evt);
this.skipToNextActiveAction();
};
Action2.prototype.execute = function(evt) {
};
Action2.prototype.skipToNextActiveAction = function() {
if (this._nextActiveAction._child) {
if (!this._nextActiveAction._child._actionManager) {
this._nextActiveAction._child._actionManager = this._actionManager;
}
this._nextActiveAction = this._nextActiveAction._child;
} else {
this._nextActiveAction = this;
}
};
Action2.prototype.then = function(action) {
this._child = action;
action._actionManager = this._actionManager;
action._prepare();
return action;
};
Action2.prototype._getProperty = function(propertyPath) {
return this._actionManager._getProperty(propertyPath);
};
Action2.prototype._getEffectiveTarget = function(target, propertyPath) {
return this._actionManager._getEffectiveTarget(target, propertyPath);
};
Action2.prototype.serialize = function(parent) {
};
Action2.prototype._serialize = function(serializedAction, parent) {
var serializationObject = {
type: 1,
children: [],
name: serializedAction.name,
properties: serializedAction.properties || []
};
if (this._child) {
this._child.serialize(serializationObject);
}
if (this._condition) {
var serializedCondition = this._condition.serialize();
serializedCondition.children.push(serializationObject);
if (parent) {
parent.children.push(serializedCondition);
}
return serializedCondition;
}
if (parent) {
parent.children.push(serializationObject);
}
return serializationObject;
};
Action2._SerializeValueAsString = function(value) {
if (typeof value === "number") {
return value.toString();
}
if (typeof value === "boolean") {
return value ? "true" : "false";
}
if (value instanceof BABYLON2.Vector2) {
return value.x + ", " + value.y;
}
if (value instanceof BABYLON2.Vector3) {
return value.x + ", " + value.y + ", " + value.z;
}
if (value instanceof BABYLON2.Color3) {
return value.r + ", " + value.g + ", " + value.b;
}
if (value instanceof BABYLON2.Color4) {
return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
}
return value;
};
Action2._GetTargetProperty = function(target) {
return {
name: "target",
targetType: target instanceof BABYLON2.Mesh ? "MeshProperties" : target instanceof BABYLON2.Light ? "LightProperties" : target instanceof BABYLON2.Camera ? "CameraProperties" : "SceneProperties",
value: target instanceof BABYLON2.Scene ? "Scene" : target.name
};
};
return Action2;
}()
);
BABYLON2.Action = Action;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ActionEvent = (
/** @class */
function() {
function ActionEvent2(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
this.source = source;
this.pointerX = pointerX;
this.pointerY = pointerY;
this.meshUnderPointer = meshUnderPointer;
this.sourceEvent = sourceEvent;
this.additionalData = additionalData;
}
ActionEvent2.CreateNew = function(source, evt, additionalData) {
var scene = source.getScene();
return new ActionEvent2(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
};
ActionEvent2.CreateNewFromSprite = function(source, scene, evt, additionalData) {
return new ActionEvent2(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
};
ActionEvent2.CreateNewFromScene = function(scene, evt) {
return new ActionEvent2(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
};
ActionEvent2.CreateNewFromPrimitive = function(prim, pointerPos, evt, additionalData) {
return new ActionEvent2(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
};
return ActionEvent2;
}()
);
BABYLON2.ActionEvent = ActionEvent;
var ActionManager = (
/** @class */
function() {
function ActionManager2(scene) {
this.actions = new Array();
this.hoverCursor = "";
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
scene.actionManagers.push(this);
}
ActionManager2.prototype.dispose = function() {
var index = this._scene.actionManagers.indexOf(this);
for (var i2 = 0; i2 < this.actions.length; i2++) {
var action = this.actions[i2];
ActionManager2.Triggers[action.trigger]--;
if (ActionManager2.Triggers[action.trigger] === 0) {
delete ActionManager2.Triggers[action.trigger];
}
}
if (index > -1) {
this._scene.actionManagers.splice(index, 1);
}
};
ActionManager2.prototype.getScene = function() {
return this._scene;
};
ActionManager2.prototype.hasSpecificTriggers = function(triggers) {
for (var index = 0; index < this.actions.length; index++) {
var action = this.actions[index];
if (triggers.indexOf(action.trigger) > -1) {
return true;
}
}
return false;
};
ActionManager2.prototype.hasSpecificTriggers2 = function(triggerA, triggerB) {
for (var index = 0; index < this.actions.length; index++) {
var action = this.actions[index];
if (triggerA == action.trigger || triggerB == action.trigger) {
return true;
}
}
return false;
};
ActionManager2.prototype.hasSpecificTrigger = function(trigger, parameterPredicate) {
for (var index = 0; index < this.actions.length; index++) {
var action = this.actions[index];
if (action.trigger === trigger) {
if (parameterPredicate) {
if (parameterPredicate(action.getTriggerParameter())) {
return true;
}
} else {
return true;
}
}
}
return false;
};
Object.defineProperty(ActionManager2.prototype, "hasPointerTriggers", {
/**
* Does this action manager has pointer triggers
*/
get: function() {
for (var index = 0; index < this.actions.length; index++) {
var action = this.actions[index];
if (action.trigger >= ActionManager2.OnPickTrigger && action.trigger <= ActionManager2.OnPointerOutTrigger) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ActionManager2.prototype, "hasPickTriggers", {
/**
* Does this action manager has pick triggers
*/
get: function() {
for (var index = 0; index < this.actions.length; index++) {
var action = this.actions[index];
if (action.trigger >= ActionManager2.OnPickTrigger && action.trigger <= ActionManager2.OnPickUpTrigger) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ActionManager2, "HasTriggers", {
/**
* Does exist one action manager with at least one trigger
**/
get: function() {
for (var t in ActionManager2.Triggers) {
if (ActionManager2.Triggers.hasOwnProperty(t)) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ActionManager2, "HasPickTriggers", {
/**
* Does exist one action manager with at least one pick trigger
**/
get: function() {
for (var t in ActionManager2.Triggers) {
if (ActionManager2.Triggers.hasOwnProperty(t)) {
var t_int = parseInt(t);
if (t_int >= ActionManager2.OnPickTrigger && t_int <= ActionManager2.OnPickUpTrigger) {
return true;
}
}
}
return false;
},
enumerable: true,
configurable: true
});
ActionManager2.HasSpecificTrigger = function(trigger) {
for (var t in ActionManager2.Triggers) {
if (ActionManager2.Triggers.hasOwnProperty(t)) {
var t_int = parseInt(t);
if (t_int === trigger) {
return true;
}
}
}
return false;
};
ActionManager2.prototype.registerAction = function(action) {
if (action.trigger === ActionManager2.OnEveryFrameTrigger) {
if (this.getScene().actionManager !== this) {
BABYLON2.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
return null;
}
}
this.actions.push(action);
if (ActionManager2.Triggers[action.trigger]) {
ActionManager2.Triggers[action.trigger]++;
} else {
ActionManager2.Triggers[action.trigger] = 1;
}
action._actionManager = this;
action._prepare();
return action;
};
ActionManager2.prototype.unregisterAction = function(action) {
var index = this.actions.indexOf(action);
if (index !== -1) {
this.actions.splice(index, 1);
ActionManager2.Triggers[action.trigger] -= 1;
if (ActionManager2.Triggers[action.trigger] === 0) {
delete ActionManager2.Triggers[action.trigger];
}
delete action._actionManager;
return true;
}
return false;
};
ActionManager2.prototype.processTrigger = function(trigger, evt) {
for (var index = 0; index < this.actions.length; index++) {
var action = this.actions[index];
if (action.trigger === trigger) {
if (evt) {
if (trigger === ActionManager2.OnKeyUpTrigger || trigger === ActionManager2.OnKeyDownTrigger) {
var parameter = action.getTriggerParameter();
if (parameter && parameter !== evt.sourceEvent.keyCode) {
if (!parameter.toLowerCase) {
continue;
}
var lowerCase = parameter.toLowerCase();
if (lowerCase !== evt.sourceEvent.key) {
var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
var actualkey = String.fromCharCode(unicode).toLowerCase();
if (actualkey !== lowerCase) {
continue;
}
}
}
}
}
action._executeCurrent(evt);
}
}
};
ActionManager2.prototype._getEffectiveTarget = function(target, propertyPath) {
var properties = propertyPath.split(".");
for (var index = 0; index < properties.length - 1; index++) {
target = target[properties[index]];
}
return target;
};
ActionManager2.prototype._getProperty = function(propertyPath) {
var properties = propertyPath.split(".");
return properties[properties.length - 1];
};
ActionManager2.prototype.serialize = function(name) {
var root = {
children: new Array(),
name,
type: 3,
properties: new Array()
// Empty for root but required
};
for (var i2 = 0; i2 < this.actions.length; i2++) {
var triggerObject = {
type: 0,
children: new Array(),
name: ActionManager2.GetTriggerName(this.actions[i2].trigger),
properties: new Array()
};
var triggerOptions = this.actions[i2].triggerOptions;
if (triggerOptions && typeof triggerOptions !== "number") {
if (triggerOptions.parameter instanceof BABYLON2.Node) {
triggerObject.properties.push(BABYLON2.Action._GetTargetProperty(triggerOptions.parameter));
} else {
var parameter = {};
BABYLON2.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
parameter._meshId = triggerOptions.parameter.mesh.id;
}
triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
}
}
this.actions[i2].serialize(triggerObject);
root.children.push(triggerObject);
}
return root;
};
ActionManager2.Parse = function(parsedActions, object, scene) {
var actionManager = new ActionManager2(scene);
if (object === null) {
scene.actionManager = actionManager;
} else {
object.actionManager = actionManager;
}
var instanciate = function(name, params) {
var newInstance = Object.create(BABYLON2.Tools.Instantiate("BABYLON." + name).prototype);
newInstance.constructor.apply(newInstance, params);
return newInstance;
};
var parseParameter = function(name, value2, target, propertyPath) {
if (propertyPath === null) {
var floatValue = parseFloat(value2);
if (value2 === "true" || value2 === "false") {
return value2 === "true";
} else {
return isNaN(floatValue) ? value2 : floatValue;
}
}
var effectiveTarget = propertyPath.split(".");
var values = value2.split(",");
for (var i3 = 0; i3 < effectiveTarget.length; i3++) {
target = target[effectiveTarget[i3]];
}
if (typeof target === "boolean") {
return values[0] === "true";
}
if (typeof target === "string") {
return values[0];
}
var split = new Array();
for (var i3 = 0; i3 < values.length; i3++) {
split.push(parseFloat(values[i3]));
}
if (target instanceof BABYLON2.Vector3) {
return BABYLON2.Vector3.FromArray(split);
}
if (target instanceof BABYLON2.Vector4) {
return BABYLON2.Vector4.FromArray(split);
}
if (target instanceof BABYLON2.Color3) {
return BABYLON2.Color3.FromArray(split);
}
if (target instanceof BABYLON2.Color4) {
return BABYLON2.Color4.FromArray(split);
}
return parseFloat(values[0]);
};
var traverse = function(parsedAction, trigger2, condition, action, combineArray) {
if (combineArray === void 0) {
combineArray = null;
}
if (parsedAction.detached) {
return;
}
var parameters = new Array();
var target = null;
var propertyPath = null;
var combine = parsedAction.combine && parsedAction.combine.length > 0;
if (parsedAction.type === 2) {
parameters.push(actionManager);
} else {
parameters.push(trigger2);
}
if (combine) {
var actions = new Array();
for (var j2 = 0; j2 < parsedAction.combine.length; j2++) {
traverse(parsedAction.combine[j2], ActionManager2.NothingTrigger, condition, action, actions);
}
parameters.push(actions);
} else {
for (var i3 = 0; i3 < parsedAction.properties.length; i3++) {
var value2 = parsedAction.properties[i3].value;
var name = parsedAction.properties[i3].name;
var targetType = parsedAction.properties[i3].targetType;
if (name === "target") {
if (targetType !== null && targetType === "SceneProperties") {
value2 = target = scene;
} else {
value2 = target = scene.getNodeByName(value2);
}
} else if (name === "parent") {
value2 = scene.getNodeByName(value2);
} else if (name === "sound") {
if (scene.getSoundByName) {
value2 = scene.getSoundByName(value2);
}
} else if (name !== "propertyPath") {
if (parsedAction.type === 2 && name === "operator") {
value2 = BABYLON2.ValueCondition[value2];
} else {
value2 = parseParameter(name, value2, target, name === "value" ? propertyPath : null);
}
} else {
propertyPath = value2;
}
parameters.push(value2);
}
}
if (combineArray === null) {
parameters.push(condition);
} else {
parameters.push(null);
}
if (parsedAction.name === "InterpolateValueAction") {
var param2 = parameters[parameters.length - 2];
parameters[parameters.length - 1] = param2;
parameters[parameters.length - 2] = condition;
}
var newAction = instanciate(parsedAction.name, parameters);
if (newAction instanceof BABYLON2.Condition && condition !== null) {
var nothing = new BABYLON2.DoNothingAction(trigger2, condition);
if (action) {
action.then(nothing);
} else {
actionManager.registerAction(nothing);
}
action = nothing;
}
if (combineArray === null) {
if (newAction instanceof BABYLON2.Condition) {
condition = newAction;
newAction = action;
} else {
condition = null;
if (action) {
action.then(newAction);
} else {
actionManager.registerAction(newAction);
}
}
} else {
combineArray.push(newAction);
}
for (var i3 = 0; i3 < parsedAction.children.length; i3++) {
traverse(parsedAction.children[i3], trigger2, condition, newAction, null);
}
};
for (var i2 = 0; i2 < parsedActions.children.length; i2++) {
var triggerParams;
var trigger = parsedActions.children[i2];
if (trigger.properties.length > 0) {
var param = trigger.properties[0].value;
var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
if (value._meshId) {
value.mesh = scene.getMeshByID(value._meshId);
}
triggerParams = { trigger: ActionManager2[trigger.name], parameter: value };
} else {
triggerParams = ActionManager2[trigger.name];
}
for (var j = 0; j < trigger.children.length; j++) {
if (!trigger.detached) {
traverse(trigger.children[j], triggerParams, null, null);
}
}
}
};
ActionManager2.GetTriggerName = function(trigger) {
switch (trigger) {
case 0:
return "NothingTrigger";
case 1:
return "OnPickTrigger";
case 2:
return "OnLeftPickTrigger";
case 3:
return "OnRightPickTrigger";
case 4:
return "OnCenterPickTrigger";
case 5:
return "OnPickDownTrigger";
case 6:
return "OnPickUpTrigger";
case 7:
return "OnLongPressTrigger";
case 8:
return "OnPointerOverTrigger";
case 9:
return "OnPointerOutTrigger";
case 10:
return "OnEveryFrameTrigger";
case 11:
return "OnIntersectionEnterTrigger";
case 12:
return "OnIntersectionExitTrigger";
case 13:
return "OnKeyDownTrigger";
case 14:
return "OnKeyUpTrigger";
case 15:
return "OnPickOutTrigger";
default:
return "";
}
};
ActionManager2.NothingTrigger = 0;
ActionManager2.OnPickTrigger = 1;
ActionManager2.OnLeftPickTrigger = 2;
ActionManager2.OnRightPickTrigger = 3;
ActionManager2.OnCenterPickTrigger = 4;
ActionManager2.OnPickDownTrigger = 5;
ActionManager2.OnDoublePickTrigger = 6;
ActionManager2.OnPickUpTrigger = 7;
ActionManager2.OnPickOutTrigger = 16;
ActionManager2.OnLongPressTrigger = 8;
ActionManager2.OnPointerOverTrigger = 9;
ActionManager2.OnPointerOutTrigger = 10;
ActionManager2.OnEveryFrameTrigger = 11;
ActionManager2.OnIntersectionEnterTrigger = 12;
ActionManager2.OnIntersectionExitTrigger = 13;
ActionManager2.OnKeyDownTrigger = 14;
ActionManager2.OnKeyUpTrigger = 15;
ActionManager2.Triggers = {};
return ActionManager2;
}()
);
BABYLON2.ActionManager = ActionManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var InterpolateValueAction = (
/** @class */
function(_super) {
__extends(InterpolateValueAction2, _super);
function InterpolateValueAction2(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
if (duration === void 0) {
duration = 1e3;
}
var _this = _super.call(this, triggerOptions, condition) || this;
_this.duration = 1e3;
_this.onInterpolationDoneObservable = new BABYLON2.Observable();
_this.propertyPath = propertyPath;
_this.value = value;
_this.duration = duration;
_this.stopOtherAnimations = stopOtherAnimations;
_this.onInterpolationDone = onInterpolationDone;
_this._target = _this._effectiveTarget = target;
return _this;
}
InterpolateValueAction2.prototype._prepare = function() {
this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
this._property = this._getProperty(this.propertyPath);
};
InterpolateValueAction2.prototype.execute = function() {
var _this = this;
var scene = this._actionManager.getScene();
var keys = [
{
frame: 0,
value: this._effectiveTarget[this._property]
},
{
frame: 100,
value: this.value
}
];
var dataType;
if (typeof this.value === "number") {
dataType = BABYLON2.Animation.ANIMATIONTYPE_FLOAT;
} else if (this.value instanceof BABYLON2.Color3) {
dataType = BABYLON2.Animation.ANIMATIONTYPE_COLOR3;
} else if (this.value instanceof BABYLON2.Vector3) {
dataType = BABYLON2.Animation.ANIMATIONTYPE_VECTOR3;
} else if (this.value instanceof BABYLON2.Matrix) {
dataType = BABYLON2.Animation.ANIMATIONTYPE_MATRIX;
} else if (this.value instanceof BABYLON2.Quaternion) {
dataType = BABYLON2.Animation.ANIMATIONTYPE_QUATERNION;
} else {
BABYLON2.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
return;
}
var animation = new BABYLON2.Animation("InterpolateValueAction", this._property, 100 * (1e3 / this.duration), dataType, BABYLON2.Animation.ANIMATIONLOOPMODE_CONSTANT);
animation.setKeys(keys);
if (this.stopOtherAnimations) {
scene.stopAnimation(this._effectiveTarget);
}
var wrapper = function() {
_this.onInterpolationDoneObservable.notifyObservers(_this);
if (_this.onInterpolationDone) {
_this.onInterpolationDone();
}
};
scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
};
InterpolateValueAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "InterpolateValueAction",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "propertyPath", value: this.propertyPath },
{ name: "value", value: BABYLON2.Action._SerializeValueAsString(this.value) },
{ name: "duration", value: BABYLON2.Action._SerializeValueAsString(this.duration) },
{ name: "stopOtherAnimations", value: BABYLON2.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
]
}, parent);
};
return InterpolateValueAction2;
}(BABYLON2.Action)
);
BABYLON2.InterpolateValueAction = InterpolateValueAction;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SwitchBooleanAction = (
/** @class */
function(_super) {
__extends(SwitchBooleanAction2, _super);
function SwitchBooleanAction2(triggerOptions, target, propertyPath, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this.propertyPath = propertyPath;
_this._target = _this._effectiveTarget = target;
return _this;
}
SwitchBooleanAction2.prototype._prepare = function() {
this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
this._property = this._getProperty(this.propertyPath);
};
SwitchBooleanAction2.prototype.execute = function() {
this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
};
SwitchBooleanAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "SwitchBooleanAction",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "propertyPath", value: this.propertyPath }
]
}, parent);
};
return SwitchBooleanAction2;
}(BABYLON2.Action)
);
BABYLON2.SwitchBooleanAction = SwitchBooleanAction;
var SetStateAction = (
/** @class */
function(_super) {
__extends(SetStateAction2, _super);
function SetStateAction2(triggerOptions, target, value, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this.value = value;
_this._target = target;
return _this;
}
SetStateAction2.prototype.execute = function() {
this._target.state = this.value;
};
SetStateAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "SetStateAction",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "value", value: this.value }
]
}, parent);
};
return SetStateAction2;
}(BABYLON2.Action)
);
BABYLON2.SetStateAction = SetStateAction;
var SetValueAction = (
/** @class */
function(_super) {
__extends(SetValueAction2, _super);
function SetValueAction2(triggerOptions, target, propertyPath, value, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this.propertyPath = propertyPath;
_this.value = value;
_this._target = _this._effectiveTarget = target;
return _this;
}
SetValueAction2.prototype._prepare = function() {
this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
this._property = this._getProperty(this.propertyPath);
};
SetValueAction2.prototype.execute = function() {
this._effectiveTarget[this._property] = this.value;
if (this._target.markAsDirty) {
this._target.markAsDirty(this._property);
}
};
SetValueAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "SetValueAction",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "propertyPath", value: this.propertyPath },
{ name: "value", value: BABYLON2.Action._SerializeValueAsString(this.value) }
]
}, parent);
};
return SetValueAction2;
}(BABYLON2.Action)
);
BABYLON2.SetValueAction = SetValueAction;
var IncrementValueAction = (
/** @class */
function(_super) {
__extends(IncrementValueAction2, _super);
function IncrementValueAction2(triggerOptions, target, propertyPath, value, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this.propertyPath = propertyPath;
_this.value = value;
_this._target = _this._effectiveTarget = target;
return _this;
}
IncrementValueAction2.prototype._prepare = function() {
this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
this._property = this._getProperty(this.propertyPath);
if (typeof this._effectiveTarget[this._property] !== "number") {
BABYLON2.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
}
};
IncrementValueAction2.prototype.execute = function() {
this._effectiveTarget[this._property] += this.value;
if (this._target.markAsDirty) {
this._target.markAsDirty(this._property);
}
};
IncrementValueAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "IncrementValueAction",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "propertyPath", value: this.propertyPath },
{ name: "value", value: BABYLON2.Action._SerializeValueAsString(this.value) }
]
}, parent);
};
return IncrementValueAction2;
}(BABYLON2.Action)
);
BABYLON2.IncrementValueAction = IncrementValueAction;
var PlayAnimationAction = (
/** @class */
function(_super) {
__extends(PlayAnimationAction2, _super);
function PlayAnimationAction2(triggerOptions, target, from, to, loop, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this.from = from;
_this.to = to;
_this.loop = loop;
_this._target = target;
return _this;
}
PlayAnimationAction2.prototype._prepare = function() {
};
PlayAnimationAction2.prototype.execute = function() {
var scene = this._actionManager.getScene();
scene.beginAnimation(this._target, this.from, this.to, this.loop);
};
PlayAnimationAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "PlayAnimationAction",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
{ name: "from", value: String(this.from) },
{ name: "to", value: String(this.to) },
{ name: "loop", value: BABYLON2.Action._SerializeValueAsString(this.loop) || false }
]
}, parent);
};
return PlayAnimationAction2;
}(BABYLON2.Action)
);
BABYLON2.PlayAnimationAction = PlayAnimationAction;
var StopAnimationAction = (
/** @class */
function(_super) {
__extends(StopAnimationAction2, _super);
function StopAnimationAction2(triggerOptions, target, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this._target = target;
return _this;
}
StopAnimationAction2.prototype._prepare = function() {
};
StopAnimationAction2.prototype.execute = function() {
var scene = this._actionManager.getScene();
scene.stopAnimation(this._target);
};
StopAnimationAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "StopAnimationAction",
properties: [BABYLON2.Action._GetTargetProperty(this._target)]
}, parent);
};
return StopAnimationAction2;
}(BABYLON2.Action)
);
BABYLON2.StopAnimationAction = StopAnimationAction;
var DoNothingAction = (
/** @class */
function(_super) {
__extends(DoNothingAction2, _super);
function DoNothingAction2(triggerOptions, condition) {
if (triggerOptions === void 0) {
triggerOptions = BABYLON2.ActionManager.NothingTrigger;
}
return _super.call(this, triggerOptions, condition) || this;
}
DoNothingAction2.prototype.execute = function() {
};
DoNothingAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "DoNothingAction",
properties: []
}, parent);
};
return DoNothingAction2;
}(BABYLON2.Action)
);
BABYLON2.DoNothingAction = DoNothingAction;
var CombineAction = (
/** @class */
function(_super) {
__extends(CombineAction2, _super);
function CombineAction2(triggerOptions, children, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this.children = children;
return _this;
}
CombineAction2.prototype._prepare = function() {
for (var index = 0; index < this.children.length; index++) {
this.children[index]._actionManager = this._actionManager;
this.children[index]._prepare();
}
};
CombineAction2.prototype.execute = function(evt) {
for (var index = 0; index < this.children.length; index++) {
this.children[index].execute(evt);
}
};
CombineAction2.prototype.serialize = function(parent) {
var serializationObject = _super.prototype._serialize.call(this, {
name: "CombineAction",
properties: [],
combine: []
}, parent);
for (var i2 = 0; i2 < this.children.length; i2++) {
serializationObject.combine.push(this.children[i2].serialize(null));
}
return serializationObject;
};
return CombineAction2;
}(BABYLON2.Action)
);
BABYLON2.CombineAction = CombineAction;
var ExecuteCodeAction = (
/** @class */
function(_super) {
__extends(ExecuteCodeAction2, _super);
function ExecuteCodeAction2(triggerOptions, func, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this.func = func;
return _this;
}
ExecuteCodeAction2.prototype.execute = function(evt) {
this.func(evt);
};
return ExecuteCodeAction2;
}(BABYLON2.Action)
);
BABYLON2.ExecuteCodeAction = ExecuteCodeAction;
var SetParentAction = (
/** @class */
function(_super) {
__extends(SetParentAction2, _super);
function SetParentAction2(triggerOptions, target, parent, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this._target = target;
_this._parent = parent;
return _this;
}
SetParentAction2.prototype._prepare = function() {
};
SetParentAction2.prototype.execute = function() {
if (this._target.parent === this._parent) {
return;
}
var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
invertParentWorldMatrix.invert();
this._target.position = BABYLON2.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
this._target.parent = this._parent;
};
SetParentAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "SetParentAction",
properties: [
BABYLON2.Action._GetTargetProperty(this._target),
BABYLON2.Action._GetTargetProperty(this._parent)
]
}, parent);
};
return SetParentAction2;
}(BABYLON2.Action)
);
BABYLON2.SetParentAction = SetParentAction;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SpriteManager = (
/** @class */
function() {
function SpriteManager2(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
if (epsilon === void 0) {
epsilon = 0.01;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
this.name = name;
this.sprites = new Array();
this.renderingGroupId = 0;
this.layerMask = 268435455;
this.fogEnabled = true;
this.isPickable = false;
this.onDisposeObservable = new BABYLON2.Observable();
this._vertexBuffers = {};
if (!scene._getComponent(BABYLON2.SceneComponentConstants.NAME_SPRITE)) {
scene._addComponent(new BABYLON2.SpriteSceneComponent(scene));
}
this._capacity = capacity;
this._spriteTexture = new BABYLON2.Texture(imgUrl, scene, true, false, samplingMode);
this._spriteTexture.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._spriteTexture.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
if (cellSize.width && cellSize.height) {
this.cellWidth = cellSize.width;
this.cellHeight = cellSize.height;
} else if (cellSize !== void 0) {
this.cellWidth = cellSize;
this.cellHeight = cellSize;
} else {
return;
}
this._epsilon = epsilon;
this._scene = scene;
this._scene.spriteManagers.push(this);
var indices = [];
var index = 0;
for (var count = 0; count < capacity; count++) {
indices.push(index);
indices.push(index + 1);
indices.push(index + 2);
indices.push(index);
indices.push(index + 2);
indices.push(index + 3);
index += 4;
}
this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
this._vertexData = new Float32Array(capacity * 16 * 4);
this._buffer = new BABYLON2.Buffer(scene.getEngine(), this._vertexData, true, 16);
var positions = this._buffer.createVertexBuffer(BABYLON2.VertexBuffer.PositionKind, 0, 4);
var options = this._buffer.createVertexBuffer("options", 4, 4);
var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
var colors = this._buffer.createVertexBuffer(BABYLON2.VertexBuffer.ColorKind, 12, 4);
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = positions;
this._vertexBuffers["options"] = options;
this._vertexBuffers["cellInfo"] = cellInfo;
this._vertexBuffers[BABYLON2.VertexBuffer.ColorKind] = colors;
this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON2.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON2.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON2.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON2.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
}
Object.defineProperty(SpriteManager2.prototype, "onDispose", {
/**
* Callback called when the manager is disposed
*/
set: function(callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SpriteManager2.prototype, "texture", {
/**
* Gets or sets the spritesheet texture
*/
get: function() {
return this._spriteTexture;
},
set: function(value) {
this._spriteTexture = value;
},
enumerable: true,
configurable: true
});
SpriteManager2.prototype._appendSpriteVertex = function(index, sprite, offsetX, offsetY, rowSize) {
var arrayOffset = index * 16;
if (offsetX === 0) {
offsetX = this._epsilon;
} else if (offsetX === 1) {
offsetX = 1 - this._epsilon;
}
if (offsetY === 0) {
offsetY = this._epsilon;
} else if (offsetY === 1) {
offsetY = 1 - this._epsilon;
}
this._vertexData[arrayOffset] = sprite.position.x;
this._vertexData[arrayOffset + 1] = sprite.position.y;
this._vertexData[arrayOffset + 2] = sprite.position.z;
this._vertexData[arrayOffset + 3] = sprite.angle;
this._vertexData[arrayOffset + 4] = sprite.width;
this._vertexData[arrayOffset + 5] = sprite.height;
this._vertexData[arrayOffset + 6] = offsetX;
this._vertexData[arrayOffset + 7] = offsetY;
this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
var offset = sprite.cellIndex / rowSize >> 0;
this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
this._vertexData[arrayOffset + 11] = offset;
this._vertexData[arrayOffset + 12] = sprite.color.r;
this._vertexData[arrayOffset + 13] = sprite.color.g;
this._vertexData[arrayOffset + 14] = sprite.color.b;
this._vertexData[arrayOffset + 15] = sprite.color.a;
};
SpriteManager2.prototype.intersects = function(ray, camera2, predicate, fastCheck) {
var count = Math.min(this._capacity, this.sprites.length);
var min = BABYLON2.Vector3.Zero();
var max = BABYLON2.Vector3.Zero();
var distance = Number.MAX_VALUE;
var currentSprite = null;
var cameraSpacePosition = BABYLON2.Vector3.Zero();
var cameraView = camera2.getViewMatrix();
for (var index = 0; index < count; index++) {
var sprite = this.sprites[index];
if (!sprite) {
continue;
}
if (predicate) {
if (!predicate(sprite)) {
continue;
}
} else if (!sprite.isPickable) {
continue;
}
BABYLON2.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
if (ray.intersectsBoxMinMax(min, max)) {
var currentDistance = BABYLON2.Vector3.Distance(cameraSpacePosition, ray.origin);
if (distance > currentDistance) {
distance = currentDistance;
currentSprite = sprite;
if (fastCheck) {
break;
}
}
}
}
if (currentSprite) {
var result = new BABYLON2.PickingInfo();
result.hit = true;
result.pickedSprite = currentSprite;
result.distance = distance;
return result;
}
return null;
};
SpriteManager2.prototype.render = function() {
if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
return;
}
var engine = this._scene.getEngine();
var baseSize = this._spriteTexture.getBaseSize();
var deltaTime = engine.getDeltaTime();
var max = Math.min(this._capacity, this.sprites.length);
var rowSize = baseSize.width / this.cellWidth;
var offset = 0;
for (var index = 0; index < max; index++) {
var sprite = this.sprites[index];
if (!sprite || !sprite.isVisible) {
continue;
}
sprite._animate(deltaTime);
this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
}
this._buffer.update(this._vertexData);
var effect = this._effectBase;
if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON2.Scene.FOGMODE_NONE && this.fogEnabled) {
effect = this._effectFog;
}
engine.enableEffect(effect);
var viewMatrix = this._scene.getViewMatrix();
effect.setTexture("diffuseSampler", this._spriteTexture);
effect.setMatrix("view", viewMatrix);
effect.setMatrix("projection", this._scene.getProjectionMatrix());
effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON2.Scene.FOGMODE_NONE && this.fogEnabled) {
effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
effect.setColor3("vFogColor", this._scene.fogColor);
}
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
if (this.blendMode == BABYLON2.Engine.ALPHA_ADD) {
engine.setAlphaMode(BABYLON2.Engine.ALPHA_ADD);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, offset / 4 * 6);
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
} else {
if (!this.noAlphaTest) {
engine.setDepthFunctionToLessOrEqual();
effect.setBool("alphaTest", true);
engine.setColorWrite(false);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, offset / 4 * 6);
engine.setColorWrite(true);
effect.setBool("alphaTest", false);
}
engine.setAlphaMode(BABYLON2.Engine.ALPHA_COMBINE);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, offset / 4 * 6);
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
}
};
SpriteManager2.prototype.dispose = function() {
if (this._buffer) {
this._buffer.dispose();
this._buffer = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
if (this._spriteTexture) {
this._spriteTexture.dispose();
this._spriteTexture = null;
}
var index = this._scene.spriteManagers.indexOf(this);
this._scene.spriteManagers.splice(index, 1);
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
};
return SpriteManager2;
}()
);
BABYLON2.SpriteManager = SpriteManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Sprite = (
/** @class */
function() {
function Sprite2(name, manager) {
this.name = name;
this.color = new BABYLON2.Color4(1, 1, 1, 1);
this.width = 1;
this.height = 1;
this.angle = 0;
this.cellIndex = 0;
this.invertU = 0;
this.invertV = 0;
this.animations = new Array();
this.isPickable = false;
this._animationStarted = false;
this._loopAnimation = false;
this._fromIndex = 0;
this._toIndex = 0;
this._delay = 0;
this._direction = 1;
this._time = 0;
this.isVisible = true;
this._manager = manager;
this._manager.sprites.push(this);
this.position = BABYLON2.Vector3.Zero();
}
Object.defineProperty(Sprite2.prototype, "size", {
/**
* Gets or sets the sprite size
*/
get: function() {
return this.width;
},
set: function(value) {
this.width = value;
this.height = value;
},
enumerable: true,
configurable: true
});
Sprite2.prototype.playAnimation = function(from, to, loop, delay, onAnimationEnd) {
this._fromIndex = from;
this._toIndex = to;
this._loopAnimation = loop;
this._delay = delay;
this._animationStarted = true;
this._direction = from < to ? 1 : -1;
this.cellIndex = from;
this._time = 0;
this._onAnimationEnd = onAnimationEnd;
};
Sprite2.prototype.stopAnimation = function() {
this._animationStarted = false;
};
Sprite2.prototype._animate = function(deltaTime) {
if (!this._animationStarted) {
return;
}
this._time += deltaTime;
if (this._time > this._delay) {
this._time = this._time % this._delay;
this.cellIndex += this._direction;
if (this.cellIndex > this._toIndex) {
if (this._loopAnimation) {
this.cellIndex = this._fromIndex;
} else {
this.cellIndex = this._toIndex;
this._animationStarted = false;
if (this._onAnimationEnd) {
this._onAnimationEnd();
}
if (this.disposeWhenFinishedAnimating) {
this.dispose();
}
}
}
}
};
Sprite2.prototype.dispose = function() {
for (var i2 = 0; i2 < this._manager.sprites.length; i2++) {
if (this._manager.sprites[i2] == this) {
this._manager.sprites.splice(i2, 1);
}
}
};
return Sprite2;
}()
);
BABYLON2.Sprite = Sprite;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Scene.prototype._internalPickSprites = function(ray, predicate, fastCheck, camera2) {
if (!BABYLON2.PickingInfo) {
return null;
}
var pickingInfo = null;
if (!camera2) {
if (!this.activeCamera) {
return null;
}
camera2 = this.activeCamera;
}
if (this.spriteManagers.length > 0) {
for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
var spriteManager = this.spriteManagers[spriteIndex];
if (!spriteManager.isPickable) {
continue;
}
var result = spriteManager.intersects(ray, camera2, predicate, fastCheck);
if (!result || !result.hit) {
continue;
}
if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
continue;
}
pickingInfo = result;
if (fastCheck) {
break;
}
}
}
return pickingInfo || new BABYLON2.PickingInfo();
};
BABYLON2.Scene.prototype.pickSprite = function(x, y, predicate, fastCheck, camera2) {
this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera2);
return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera2);
};
BABYLON2.Scene.prototype.pickSpriteWithRay = function(ray, predicate, fastCheck, camera2) {
if (!this._tempSpritePickingRay) {
return null;
}
if (!camera2) {
if (!this.activeCamera) {
return null;
}
camera2 = this.activeCamera;
}
BABYLON2.Ray.TransformToRef(ray, camera2.getViewMatrix(), this._tempSpritePickingRay);
return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera2);
};
BABYLON2.Scene.prototype.setPointerOverSprite = function(sprite) {
if (this._pointerOverSprite === sprite) {
return;
}
if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
this._pointerOverSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnPointerOutTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
}
this._pointerOverSprite = sprite;
if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
this._pointerOverSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnPointerOverTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
}
};
BABYLON2.Scene.prototype.getPointerOverSprite = function() {
return this._pointerOverSprite;
};
var SpriteSceneComponent = (
/** @class */
function() {
function SpriteSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_SPRITE;
this.scene = scene;
this.scene.spriteManagers = new Array();
this.scene._tempSpritePickingRay = BABYLON2.Ray ? BABYLON2.Ray.Zero() : null;
this.scene.onBeforeSpritesRenderingObservable = new BABYLON2.Observable();
this.scene.onAfterSpritesRenderingObservable = new BABYLON2.Observable();
this._spritePredicate = function(sprite) {
if (!sprite.actionManager) {
return false;
}
return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
};
}
SpriteSceneComponent2.prototype.register = function() {
this.scene._pointerMoveStage.registerStep(BABYLON2.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
this.scene._pointerDownStage.registerStep(BABYLON2.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
this.scene._pointerUpStage.registerStep(BABYLON2.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
};
SpriteSceneComponent2.prototype.rebuild = function() {
};
SpriteSceneComponent2.prototype.dispose = function() {
this.scene.onBeforeSpritesRenderingObservable.clear();
this.scene.onAfterSpritesRenderingObservable.clear();
var spriteManagers = this.scene.spriteManagers;
while (spriteManagers.length) {
spriteManagers[0].dispose();
}
};
SpriteSceneComponent2.prototype._pickSpriteButKeepRay = function(originalPointerInfo, x, y, fastCheck, camera2) {
var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera2);
if (result) {
result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
}
return result;
};
SpriteSceneComponent2.prototype._pointerMove = function(unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas2) {
var scene = this.scene;
if (isMeshPicked) {
scene.setPointerOverSprite(null);
} else {
pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || void 0);
if (pickResult && pickResult.hit && pickResult.pickedSprite) {
scene.setPointerOverSprite(pickResult.pickedSprite);
if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
canvas2.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
} else {
canvas2.style.cursor = scene.hoverCursor;
}
} else {
scene.setPointerOverSprite(null);
}
}
return pickResult;
};
SpriteSceneComponent2.prototype._pointerDown = function(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
var scene = this.scene;
scene._pickedDownSprite = null;
if (scene.spriteManagers.length > 0) {
pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || void 0);
if (pickResult && pickResult.hit && pickResult.pickedSprite) {
if (pickResult.pickedSprite.actionManager) {
scene._pickedDownSprite = pickResult.pickedSprite;
switch (evt.button) {
case 0:
pickResult.pickedSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnLeftPickTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
break;
case 1:
pickResult.pickedSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnCenterPickTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
break;
case 2:
pickResult.pickedSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnRightPickTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
break;
}
if (pickResult.pickedSprite.actionManager) {
pickResult.pickedSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnPickDownTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
}
}
}
}
return pickResult;
};
SpriteSceneComponent2.prototype._pointerUp = function(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
var scene = this.scene;
if (scene.spriteManagers.length > 0) {
var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || void 0);
if (spritePickResult) {
if (spritePickResult.hit && spritePickResult.pickedSprite) {
if (spritePickResult.pickedSprite.actionManager) {
spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnPickUpTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
if (spritePickResult.pickedSprite.actionManager) {
if (!this.scene._isPointerSwiping()) {
spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnPickTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
}
}
}
}
if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
scene._pickedDownSprite.actionManager.processTrigger(BABYLON2.ActionManager.OnPickOutTrigger, BABYLON2.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
}
}
}
return pickResult;
};
return SpriteSceneComponent2;
}()
);
BABYLON2.SpriteSceneComponent = SpriteSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var IntersectionInfo = (
/** @class */
function() {
function IntersectionInfo2(bu, bv, distance) {
this.bu = bu;
this.bv = bv;
this.distance = distance;
this.faceId = 0;
this.subMeshId = 0;
}
return IntersectionInfo2;
}()
);
BABYLON2.IntersectionInfo = IntersectionInfo;
var PickingInfo = (
/** @class */
function() {
function PickingInfo2() {
this.hit = false;
this.distance = 0;
this.pickedPoint = null;
this.pickedMesh = null;
this.bu = 0;
this.bv = 0;
this.faceId = -1;
this.subMeshId = 0;
this.pickedSprite = null;
this.originMesh = null;
this.ray = null;
}
PickingInfo2.prototype.getNormal = function(useWorldCoordinates, useVerticesNormals) {
if (useWorldCoordinates === void 0) {
useWorldCoordinates = false;
}
if (useVerticesNormals === void 0) {
useVerticesNormals = true;
}
if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
return null;
}
var indices = this.pickedMesh.getIndices();
if (!indices) {
return null;
}
var result;
if (useVerticesNormals) {
var normals = this.pickedMesh.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var normal0 = BABYLON2.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
var normal1 = BABYLON2.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
var normal2 = BABYLON2.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
normal0 = normal0.scale(this.bu);
normal1 = normal1.scale(this.bv);
normal2 = normal2.scale(1 - this.bu - this.bv);
result = new BABYLON2.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
} else {
var positions = this.pickedMesh.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var vertex1 = BABYLON2.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
var vertex2 = BABYLON2.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
var vertex3 = BABYLON2.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
var p1p2 = vertex1.subtract(vertex2);
var p3p2 = vertex3.subtract(vertex2);
result = BABYLON2.Vector3.Cross(p1p2, p3p2);
}
if (useWorldCoordinates) {
var wm = this.pickedMesh.getWorldMatrix();
if (this.pickedMesh.nonUniformScaling) {
BABYLON2.Tmp.Matrix[0].copyFrom(wm);
wm = BABYLON2.Tmp.Matrix[0];
wm.setTranslationFromFloats(0, 0, 0);
wm.invert();
wm.transposeToRef(BABYLON2.Tmp.Matrix[1]);
wm = BABYLON2.Tmp.Matrix[1];
}
result = BABYLON2.Vector3.TransformNormal(result, wm);
}
result.normalize();
return result;
};
PickingInfo2.prototype.getTextureCoordinates = function() {
if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
return null;
}
var indices = this.pickedMesh.getIndices();
if (!indices) {
return null;
}
var uvs = this.pickedMesh.getVerticesData(BABYLON2.VertexBuffer.UVKind);
if (!uvs) {
return null;
}
var uv0 = BABYLON2.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
var uv1 = BABYLON2.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
var uv2 = BABYLON2.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
uv0 = uv0.scale(1 - this.bu - this.bv);
uv1 = uv1.scale(this.bu);
uv2 = uv2.scale(this.bv);
return new BABYLON2.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
};
return PickingInfo2;
}()
);
BABYLON2.PickingInfo = PickingInfo;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Ray = (
/** @class */
function() {
function Ray2(origin, direction, length) {
if (length === void 0) {
length = Number.MAX_VALUE;
}
this.origin = origin;
this.direction = direction;
this.length = length;
}
Ray2.prototype.intersectsBoxMinMax = function(minimum, maximum) {
var d = 0;
var maxValue = Number.MAX_VALUE;
var inv;
var min;
var max;
var temp;
if (Math.abs(this.direction.x) < 1e-7) {
if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
return false;
}
} else {
inv = 1 / this.direction.x;
min = (minimum.x - this.origin.x) * inv;
max = (maximum.x - this.origin.x) * inv;
if (max === -Infinity) {
max = Infinity;
}
if (min > max) {
temp = min;
min = max;
max = temp;
}
d = Math.max(min, d);
maxValue = Math.min(max, maxValue);
if (d > maxValue) {
return false;
}
}
if (Math.abs(this.direction.y) < 1e-7) {
if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
return false;
}
} else {
inv = 1 / this.direction.y;
min = (minimum.y - this.origin.y) * inv;
max = (maximum.y - this.origin.y) * inv;
if (max === -Infinity) {
max = Infinity;
}
if (min > max) {
temp = min;
min = max;
max = temp;
}
d = Math.max(min, d);
maxValue = Math.min(max, maxValue);
if (d > maxValue) {
return false;
}
}
if (Math.abs(this.direction.z) < 1e-7) {
if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
return false;
}
} else {
inv = 1 / this.direction.z;
min = (minimum.z - this.origin.z) * inv;
max = (maximum.z - this.origin.z) * inv;
if (max === -Infinity) {
max = Infinity;
}
if (min > max) {
temp = min;
min = max;
max = temp;
}
d = Math.max(min, d);
maxValue = Math.min(max, maxValue);
if (d > maxValue) {
return false;
}
}
return true;
};
Ray2.prototype.intersectsBox = function(box) {
return this.intersectsBoxMinMax(box.minimum, box.maximum);
};
Ray2.prototype.intersectsSphere = function(sphere) {
var x = sphere.center.x - this.origin.x;
var y = sphere.center.y - this.origin.y;
var z = sphere.center.z - this.origin.z;
var pyth = x * x + y * y + z * z;
var rr = sphere.radius * sphere.radius;
if (pyth <= rr) {
return true;
}
var dot = x * this.direction.x + y * this.direction.y + z * this.direction.z;
if (dot < 0) {
return false;
}
var temp = pyth - dot * dot;
return temp <= rr;
};
Ray2.prototype.intersectsTriangle = function(vertex0, vertex1, vertex2) {
if (!this._edge1) {
this._edge1 = BABYLON2.Vector3.Zero();
this._edge2 = BABYLON2.Vector3.Zero();
this._pvec = BABYLON2.Vector3.Zero();
this._tvec = BABYLON2.Vector3.Zero();
this._qvec = BABYLON2.Vector3.Zero();
}
vertex1.subtractToRef(vertex0, this._edge1);
vertex2.subtractToRef(vertex0, this._edge2);
BABYLON2.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
var det = BABYLON2.Vector3.Dot(this._edge1, this._pvec);
if (det === 0) {
return null;
}
var invdet = 1 / det;
this.origin.subtractToRef(vertex0, this._tvec);
var bu = BABYLON2.Vector3.Dot(this._tvec, this._pvec) * invdet;
if (bu < 0 || bu > 1) {
return null;
}
BABYLON2.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
var bv = BABYLON2.Vector3.Dot(this.direction, this._qvec) * invdet;
if (bv < 0 || bu + bv > 1) {
return null;
}
var distance = BABYLON2.Vector3.Dot(this._edge2, this._qvec) * invdet;
if (distance > this.length) {
return null;
}
return new BABYLON2.IntersectionInfo(bu, bv, distance);
};
Ray2.prototype.intersectsPlane = function(plane) {
var distance;
var result1 = BABYLON2.Vector3.Dot(plane.normal, this.direction);
if (Math.abs(result1) < 999999997475243e-21) {
return null;
} else {
var result2 = BABYLON2.Vector3.Dot(plane.normal, this.origin);
distance = (-plane.d - result2) / result1;
if (distance < 0) {
if (distance < -999999997475243e-21) {
return null;
} else {
return 0;
}
}
return distance;
}
};
Ray2.prototype.intersectsMesh = function(mesh2, fastCheck) {
var tm = BABYLON2.Tmp.Matrix[0];
mesh2.getWorldMatrix().invertToRef(tm);
if (this._tmpRay) {
Ray2.TransformToRef(this, tm, this._tmpRay);
} else {
this._tmpRay = Ray2.Transform(this, tm);
}
return mesh2.intersects(this._tmpRay, fastCheck);
};
Ray2.prototype.intersectsMeshes = function(meshes, fastCheck, results) {
if (results) {
results.length = 0;
} else {
results = [];
}
for (var i2 = 0; i2 < meshes.length; i2++) {
var pickInfo = this.intersectsMesh(meshes[i2], fastCheck);
if (pickInfo.hit) {
results.push(pickInfo);
}
}
results.sort(this._comparePickingInfo);
return results;
};
Ray2.prototype._comparePickingInfo = function(pickingInfoA, pickingInfoB) {
if (pickingInfoA.distance < pickingInfoB.distance) {
return -1;
} else if (pickingInfoA.distance > pickingInfoB.distance) {
return 1;
} else {
return 0;
}
};
Ray2.prototype.intersectionSegment = function(sega, segb, threshold) {
var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray2.rayl, Ray2.rayl, Ray2.rayl));
var u = segb.subtract(sega);
var v = rsegb.subtract(this.origin);
var w = sega.subtract(this.origin);
var a = BABYLON2.Vector3.Dot(u, u);
var b2 = BABYLON2.Vector3.Dot(u, v);
var c = BABYLON2.Vector3.Dot(v, v);
var d = BABYLON2.Vector3.Dot(u, w);
var e2 = BABYLON2.Vector3.Dot(v, w);
var D = a * c - b2 * b2;
var sc, sN, sD = D;
var tc, tN, tD = D;
if (D < Ray2.smallnum) {
sN = 0;
sD = 1;
tN = e2;
tD = c;
} else {
sN = b2 * e2 - c * d;
tN = a * e2 - b2 * d;
if (sN < 0) {
sN = 0;
tN = e2;
tD = c;
} else if (sN > sD) {
sN = sD;
tN = e2 + b2;
tD = c;
}
}
if (tN < 0) {
tN = 0;
if (-d < 0) {
sN = 0;
} else if (-d > a) {
sN = sD;
} else {
sN = -d;
sD = a;
}
} else if (tN > tD) {
tN = tD;
if (-d + b2 < 0) {
sN = 0;
} else if (-d + b2 > a) {
sN = sD;
} else {
sN = -d + b2;
sD = a;
}
}
sc = Math.abs(sN) < Ray2.smallnum ? 0 : sN / sD;
tc = Math.abs(tN) < Ray2.smallnum ? 0 : tN / tD;
var qtc = v.multiplyByFloats(tc, tc, tc);
var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc);
var isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold;
if (isIntersected) {
return qtc.length();
}
return -1;
};
Ray2.prototype.update = function(x, y, viewportWidth, viewportHeight, world, view, projection) {
BABYLON2.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
BABYLON2.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON2.Tmp.Vector3[0]);
BABYLON2.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
this.direction.normalize();
return this;
};
Ray2.Zero = function() {
return new Ray2(BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero());
};
Ray2.CreateNew = function(x, y, viewportWidth, viewportHeight, world, view, projection) {
var result = Ray2.Zero();
return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
};
Ray2.CreateNewFromTo = function(origin, end, world) {
if (world === void 0) {
world = BABYLON2.Matrix.Identity();
}
var direction = end.subtract(origin);
var length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z);
direction.normalize();
return Ray2.Transform(new Ray2(origin, direction, length), world);
};
Ray2.Transform = function(ray, matrix) {
var result = new Ray2(new BABYLON2.Vector3(0, 0, 0), new BABYLON2.Vector3(0, 0, 0));
Ray2.TransformToRef(ray, matrix, result);
return result;
};
Ray2.TransformToRef = function(ray, matrix, result) {
BABYLON2.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
BABYLON2.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
result.length = ray.length;
var dir = result.direction;
var len = dir.length();
if (!(len === 0 || len === 1)) {
var num = 1 / len;
dir.x *= num;
dir.y *= num;
dir.z *= num;
result.length *= len;
}
};
Ray2.smallnum = 1e-8;
Ray2.rayl = 1e9;
return Ray2;
}()
);
BABYLON2.Ray = Ray;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var intersectBoxAASphere = function(boxMin, boxMax, sphereCenter, sphereRadius) {
if (boxMin.x > sphereCenter.x + sphereRadius) {
return false;
}
if (sphereCenter.x - sphereRadius > boxMax.x) {
return false;
}
if (boxMin.y > sphereCenter.y + sphereRadius) {
return false;
}
if (sphereCenter.y - sphereRadius > boxMax.y) {
return false;
}
if (boxMin.z > sphereCenter.z + sphereRadius) {
return false;
}
if (sphereCenter.z - sphereRadius > boxMax.z) {
return false;
}
return true;
};
var getLowestRoot = function() {
var result = { root: 0, found: false };
return function(a, b2, c, maxR) {
result.root = 0;
result.found = false;
var determinant = b2 * b2 - 4 * a * c;
if (determinant < 0) {
return result;
}
var sqrtD = Math.sqrt(determinant);
var r1 = (-b2 - sqrtD) / (2 * a);
var r2 = (-b2 + sqrtD) / (2 * a);
if (r1 > r2) {
var temp = r2;
r2 = r1;
r1 = temp;
}
if (r1 > 0 && r1 < maxR) {
result.root = r1;
result.found = true;
return result;
}
if (r2 > 0 && r2 < maxR) {
result.root = r2;
result.found = true;
return result;
}
return result;
};
}();
var Collider2 = (
/** @class */
function() {
function Collider3() {
this._collisionPoint = BABYLON2.Vector3.Zero();
this._planeIntersectionPoint = BABYLON2.Vector3.Zero();
this._tempVector = BABYLON2.Vector3.Zero();
this._tempVector2 = BABYLON2.Vector3.Zero();
this._tempVector3 = BABYLON2.Vector3.Zero();
this._tempVector4 = BABYLON2.Vector3.Zero();
this._edge = BABYLON2.Vector3.Zero();
this._baseToVertex = BABYLON2.Vector3.Zero();
this._destinationPoint = BABYLON2.Vector3.Zero();
this._slidePlaneNormal = BABYLON2.Vector3.Zero();
this._displacementVector = BABYLON2.Vector3.Zero();
this._radius = BABYLON2.Vector3.One();
this._retry = 0;
this._basePointWorld = BABYLON2.Vector3.Zero();
this._velocityWorld = BABYLON2.Vector3.Zero();
this._normalizedVelocity = BABYLON2.Vector3.Zero();
this._collisionMask = -1;
}
Object.defineProperty(Collider3.prototype, "collisionMask", {
get: function() {
return this._collisionMask;
},
set: function(mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Collider3.prototype, "slidePlaneNormal", {
/**
* Gets the plane normal used to compute the sliding response (in local space)
*/
get: function() {
return this._slidePlaneNormal;
},
enumerable: true,
configurable: true
});
Collider3.prototype._initialize = function(source, dir, e2) {
this._velocity = dir;
BABYLON2.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
this._basePoint = source;
source.multiplyToRef(this._radius, this._basePointWorld);
dir.multiplyToRef(this._radius, this._velocityWorld);
this._velocityWorldLength = this._velocityWorld.length();
this._epsilon = e2;
this.collisionFound = false;
};
Collider3.prototype._checkPointInTriangle = function(point, pa, pb, pc, n) {
pa.subtractToRef(point, this._tempVector);
pb.subtractToRef(point, this._tempVector2);
BABYLON2.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
var d = BABYLON2.Vector3.Dot(this._tempVector4, n);
if (d < 0) {
return false;
}
pc.subtractToRef(point, this._tempVector3);
BABYLON2.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
d = BABYLON2.Vector3.Dot(this._tempVector4, n);
if (d < 0) {
return false;
}
BABYLON2.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
d = BABYLON2.Vector3.Dot(this._tempVector4, n);
return d >= 0;
};
Collider3.prototype._canDoCollision = function(sphereCenter, sphereRadius, vecMin, vecMax) {
var distance = BABYLON2.Vector3.Distance(this._basePointWorld, sphereCenter);
var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
if (distance > this._velocityWorldLength + max + sphereRadius) {
return false;
}
if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
return false;
}
return true;
};
Collider3.prototype._testTriangle = function(faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
var t0;
var embeddedInPlane = false;
if (!trianglePlaneArray) {
trianglePlaneArray = [];
}
if (!trianglePlaneArray[faceIndex]) {
trianglePlaneArray[faceIndex] = new BABYLON2.Plane(0, 0, 0, 0);
trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
}
var trianglePlane = trianglePlaneArray[faceIndex];
if (!hasMaterial && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
return;
}
var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
var normalDotVelocity = BABYLON2.Vector3.Dot(trianglePlane.normal, this._velocity);
if (normalDotVelocity == 0) {
if (Math.abs(signedDistToTrianglePlane) >= 1) {
return;
}
embeddedInPlane = true;
t0 = 0;
} else {
t0 = (-1 - signedDistToTrianglePlane) / normalDotVelocity;
var t1 = (1 - signedDistToTrianglePlane) / normalDotVelocity;
if (t0 > t1) {
var temp = t1;
t1 = t0;
t0 = temp;
}
if (t0 > 1 || t1 < 0) {
return;
}
if (t0 < 0) {
t0 = 0;
}
if (t0 > 1) {
t0 = 1;
}
}
this._collisionPoint.copyFromFloats(0, 0, 0);
var found = false;
var t = 1;
if (!embeddedInPlane) {
this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
this._velocity.scaleToRef(t0, this._tempVector);
this._planeIntersectionPoint.addInPlace(this._tempVector);
if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
found = true;
t = t0;
this._collisionPoint.copyFrom(this._planeIntersectionPoint);
}
}
if (!found) {
var velocitySquaredLength = this._velocity.lengthSquared();
var a = velocitySquaredLength;
this._basePoint.subtractToRef(p1, this._tempVector);
var b2 = 2 * BABYLON2.Vector3.Dot(this._velocity, this._tempVector);
var c = this._tempVector.lengthSquared() - 1;
var lowestRoot = getLowestRoot(a, b2, c, t);
if (lowestRoot.found) {
t = lowestRoot.root;
found = true;
this._collisionPoint.copyFrom(p1);
}
this._basePoint.subtractToRef(p2, this._tempVector);
b2 = 2 * BABYLON2.Vector3.Dot(this._velocity, this._tempVector);
c = this._tempVector.lengthSquared() - 1;
lowestRoot = getLowestRoot(a, b2, c, t);
if (lowestRoot.found) {
t = lowestRoot.root;
found = true;
this._collisionPoint.copyFrom(p2);
}
this._basePoint.subtractToRef(p3, this._tempVector);
b2 = 2 * BABYLON2.Vector3.Dot(this._velocity, this._tempVector);
c = this._tempVector.lengthSquared() - 1;
lowestRoot = getLowestRoot(a, b2, c, t);
if (lowestRoot.found) {
t = lowestRoot.root;
found = true;
this._collisionPoint.copyFrom(p3);
}
p2.subtractToRef(p1, this._edge);
p1.subtractToRef(this._basePoint, this._baseToVertex);
var edgeSquaredLength = this._edge.lengthSquared();
var edgeDotVelocity = BABYLON2.Vector3.Dot(this._edge, this._velocity);
var edgeDotBaseToVertex = BABYLON2.Vector3.Dot(this._edge, this._baseToVertex);
a = edgeSquaredLength * -velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;
b2 = edgeSquaredLength * (2 * BABYLON2.Vector3.Dot(this._velocity, this._baseToVertex)) - 2 * edgeDotVelocity * edgeDotBaseToVertex;
c = edgeSquaredLength * (1 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
lowestRoot = getLowestRoot(a, b2, c, t);
if (lowestRoot.found) {
var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
if (f >= 0 && f <= 1) {
t = lowestRoot.root;
found = true;
this._edge.scaleInPlace(f);
p1.addToRef(this._edge, this._collisionPoint);
}
}
p3.subtractToRef(p2, this._edge);
p2.subtractToRef(this._basePoint, this._baseToVertex);
edgeSquaredLength = this._edge.lengthSquared();
edgeDotVelocity = BABYLON2.Vector3.Dot(this._edge, this._velocity);
edgeDotBaseToVertex = BABYLON2.Vector3.Dot(this._edge, this._baseToVertex);
a = edgeSquaredLength * -velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;
b2 = edgeSquaredLength * (2 * BABYLON2.Vector3.Dot(this._velocity, this._baseToVertex)) - 2 * edgeDotVelocity * edgeDotBaseToVertex;
c = edgeSquaredLength * (1 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
lowestRoot = getLowestRoot(a, b2, c, t);
if (lowestRoot.found) {
f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
if (f >= 0 && f <= 1) {
t = lowestRoot.root;
found = true;
this._edge.scaleInPlace(f);
p2.addToRef(this._edge, this._collisionPoint);
}
}
p1.subtractToRef(p3, this._edge);
p3.subtractToRef(this._basePoint, this._baseToVertex);
edgeSquaredLength = this._edge.lengthSquared();
edgeDotVelocity = BABYLON2.Vector3.Dot(this._edge, this._velocity);
edgeDotBaseToVertex = BABYLON2.Vector3.Dot(this._edge, this._baseToVertex);
a = edgeSquaredLength * -velocitySquaredLength + edgeDotVelocity * edgeDotVelocity;
b2 = edgeSquaredLength * (2 * BABYLON2.Vector3.Dot(this._velocity, this._baseToVertex)) - 2 * edgeDotVelocity * edgeDotBaseToVertex;
c = edgeSquaredLength * (1 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
lowestRoot = getLowestRoot(a, b2, c, t);
if (lowestRoot.found) {
f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
if (f >= 0 && f <= 1) {
t = lowestRoot.root;
found = true;
this._edge.scaleInPlace(f);
p3.addToRef(this._edge, this._collisionPoint);
}
}
}
if (found) {
var distToCollision = t * this._velocity.length();
if (!this.collisionFound || distToCollision < this._nearestDistance) {
if (!this.intersectionPoint) {
this.intersectionPoint = this._collisionPoint.clone();
} else {
this.intersectionPoint.copyFrom(this._collisionPoint);
}
this._nearestDistance = distToCollision;
this.collisionFound = true;
}
}
};
Collider3.prototype._collide = function(trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
for (var i2 = indexStart; i2 < indexEnd; i2 += 3) {
var p1 = pts[indices[i2] - decal];
var p2 = pts[indices[i2 + 1] - decal];
var p3 = pts[indices[i2 + 2] - decal];
this._testTriangle(i2, trianglePlaneArray, p3, p2, p1, hasMaterial);
}
};
Collider3.prototype._getResponse = function(pos, vel) {
pos.addToRef(vel, this._destinationPoint);
vel.scaleInPlace(this._nearestDistance / vel.length());
this._basePoint.addToRef(vel, pos);
pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
this._slidePlaneNormal.normalize();
this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
pos.addInPlace(this._displacementVector);
this.intersectionPoint.addInPlace(this._displacementVector);
this._slidePlaneNormal.scaleInPlace(BABYLON2.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
};
return Collider3;
}()
);
BABYLON2.Collider = Collider2;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.CollisionWorker = "";
var WorkerTaskType;
(function(WorkerTaskType2) {
WorkerTaskType2[WorkerTaskType2["INIT"] = 0] = "INIT";
WorkerTaskType2[WorkerTaskType2["UPDATE"] = 1] = "UPDATE";
WorkerTaskType2[WorkerTaskType2["COLLIDE"] = 2] = "COLLIDE";
})(WorkerTaskType = BABYLON2.WorkerTaskType || (BABYLON2.WorkerTaskType = {}));
var WorkerReplyType;
(function(WorkerReplyType2) {
WorkerReplyType2[WorkerReplyType2["SUCCESS"] = 0] = "SUCCESS";
WorkerReplyType2[WorkerReplyType2["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
})(WorkerReplyType = BABYLON2.WorkerReplyType || (BABYLON2.WorkerReplyType = {}));
var CollisionCoordinatorWorker = (
/** @class */
function() {
function CollisionCoordinatorWorker2() {
var _this = this;
this._scaledPosition = BABYLON2.Vector3.Zero();
this._scaledVelocity = BABYLON2.Vector3.Zero();
this.onMeshUpdated = function(transformNode) {
_this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker2.SerializeMesh(transformNode);
};
this.onGeometryUpdated = function(geometry) {
_this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker2.SerializeGeometry(geometry);
};
this._afterRender = function() {
if (!_this._init) {
return;
}
if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
return;
}
if (_this._runningUpdated > 4) {
return;
}
++_this._runningUpdated;
var payload = {
updatedMeshes: _this._addUpdateMeshesList,
updatedGeometries: _this._addUpdateGeometriesList,
removedGeometries: _this._toRemoveGeometryArray,
removedMeshes: _this._toRemoveMeshesArray
};
var message = {
payload,
taskType: WorkerTaskType.UPDATE
};
var serializable = [];
for (var id in payload.updatedGeometries) {
if (payload.updatedGeometries.hasOwnProperty(id)) {
serializable.push(message.payload.updatedGeometries[id].indices.buffer);
serializable.push(message.payload.updatedGeometries[id].normals.buffer);
serializable.push(message.payload.updatedGeometries[id].positions.buffer);
}
}
_this._worker.postMessage(message, serializable);
_this._addUpdateMeshesList = {};
_this._addUpdateGeometriesList = {};
_this._toRemoveGeometryArray = [];
_this._toRemoveMeshesArray = [];
};
this._onMessageFromWorker = function(e2) {
var returnData = e2.data;
if (returnData.error != WorkerReplyType.SUCCESS) {
BABYLON2.Tools.Warn("error returned from worker!");
return;
}
switch (returnData.taskType) {
case WorkerTaskType.INIT:
_this._init = true;
_this._scene.meshes.forEach(function(mesh3) {
_this.onMeshAdded(mesh3);
});
_this._scene.getGeometries().forEach(function(geometry) {
_this.onGeometryAdded(geometry);
});
break;
case WorkerTaskType.UPDATE:
_this._runningUpdated--;
break;
case WorkerTaskType.COLLIDE:
var returnPayload = returnData.payload;
if (!_this._collisionsCallbackArray[returnPayload.collisionId]) {
return;
}
var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
if (callback) {
var mesh2 = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
if (mesh2) {
callback(returnPayload.collisionId, BABYLON2.Vector3.FromArray(returnPayload.newPosition), mesh2);
}
}
_this._collisionsCallbackArray[returnPayload.collisionId] = null;
break;
}
};
this._collisionsCallbackArray = [];
this._init = false;
this._runningUpdated = 0;
this._addUpdateMeshesList = {};
this._addUpdateGeometriesList = {};
this._toRemoveGeometryArray = [];
this._toRemoveMeshesArray = [];
}
CollisionCoordinatorWorker2.prototype.getNewPosition = function(position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
if (!this._init) {
return;
}
if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 1e5]) {
return;
}
position.divideToRef(collider._radius, this._scaledPosition);
displacement.divideToRef(collider._radius, this._scaledVelocity);
this._collisionsCallbackArray[collisionIndex] = onNewPosition;
var payload = {
collider: {
position: this._scaledPosition.asArray(),
velocity: this._scaledVelocity.asArray(),
radius: collider._radius.asArray()
},
collisionId: collisionIndex,
excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
maximumRetry
};
var message = {
payload,
taskType: WorkerTaskType.COLLIDE
};
this._worker.postMessage(message);
};
CollisionCoordinatorWorker2.prototype.init = function(scene) {
this._scene = scene;
this._scene.registerAfterRender(this._afterRender);
var workerUrl = BABYLON2.WorkerIncluded ? BABYLON2.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON2.CollisionWorker], { type: "application/javascript" }));
this._worker = new Worker(workerUrl);
this._worker.onmessage = this._onMessageFromWorker;
var message = {
payload: {},
taskType: WorkerTaskType.INIT
};
this._worker.postMessage(message);
};
CollisionCoordinatorWorker2.prototype.destroy = function() {
this._scene.unregisterAfterRender(this._afterRender);
this._worker.terminate();
};
CollisionCoordinatorWorker2.prototype.onMeshAdded = function(mesh2) {
mesh2.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
this.onMeshUpdated(mesh2);
};
CollisionCoordinatorWorker2.prototype.onMeshRemoved = function(mesh2) {
this._toRemoveMeshesArray.push(mesh2.uniqueId);
};
CollisionCoordinatorWorker2.prototype.onGeometryAdded = function(geometry) {
geometry.onGeometryUpdated = this.onGeometryUpdated;
this.onGeometryUpdated(geometry);
};
CollisionCoordinatorWorker2.prototype.onGeometryDeleted = function(geometry) {
this._toRemoveGeometryArray.push(geometry.id);
};
CollisionCoordinatorWorker2.SerializeMesh = function(mesh2) {
var submeshes = [];
if (mesh2.subMeshes) {
submeshes = mesh2.subMeshes.map(function(sm, idx) {
var boundingInfo2 = sm.getBoundingInfo();
return {
position: idx,
verticesStart: sm.verticesStart,
verticesCount: sm.verticesCount,
indexStart: sm.indexStart,
indexCount: sm.indexCount,
hasMaterial: !!sm.getMaterial(),
sphereCenter: boundingInfo2.boundingSphere.centerWorld.asArray(),
sphereRadius: boundingInfo2.boundingSphere.radiusWorld,
boxMinimum: boundingInfo2.boundingBox.minimumWorld.asArray(),
boxMaximum: boundingInfo2.boundingBox.maximumWorld.asArray()
};
});
}
var geometryId = null;
if (mesh2 instanceof BABYLON2.Mesh) {
var geometry = mesh2.geometry;
geometryId = geometry ? geometry.id : null;
} else if (mesh2 instanceof BABYLON2.InstancedMesh) {
var geometry = mesh2.sourceMesh && mesh2.sourceMesh.geometry;
geometryId = geometry ? geometry.id : null;
}
var boundingInfo = mesh2.getBoundingInfo();
return {
uniqueId: mesh2.uniqueId,
id: mesh2.id,
name: mesh2.name,
geometryId,
sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
sphereRadius: boundingInfo.boundingSphere.radiusWorld,
boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
worldMatrixFromCache: mesh2.worldMatrixFromCache.asArray(),
subMeshes: submeshes,
checkCollisions: mesh2.checkCollisions
};
};
CollisionCoordinatorWorker2.SerializeGeometry = function(geometry) {
return {
id: geometry.id,
positions: new Float32Array(geometry.getVerticesData(BABYLON2.VertexBuffer.PositionKind) || []),
normals: new Float32Array(geometry.getVerticesData(BABYLON2.VertexBuffer.NormalKind) || []),
indices: new Uint32Array(geometry.getIndices() || [])
};
};
return CollisionCoordinatorWorker2;
}()
);
BABYLON2.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
var CollisionCoordinatorLegacy = (
/** @class */
function() {
function CollisionCoordinatorLegacy2() {
this._scaledPosition = BABYLON2.Vector3.Zero();
this._scaledVelocity = BABYLON2.Vector3.Zero();
this._finalPosition = BABYLON2.Vector3.Zero();
}
CollisionCoordinatorLegacy2.prototype.getNewPosition = function(position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
position.divideToRef(collider._radius, this._scaledPosition);
displacement.divideToRef(collider._radius, this._scaledVelocity);
collider.collidedMesh = null;
collider._retry = 0;
collider._initialVelocity = this._scaledVelocity;
collider._initialPosition = this._scaledPosition;
this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
this._finalPosition.multiplyInPlace(collider._radius);
onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
};
CollisionCoordinatorLegacy2.prototype.init = function(scene) {
this._scene = scene;
};
CollisionCoordinatorLegacy2.prototype.destroy = function() {
};
CollisionCoordinatorLegacy2.prototype.onMeshAdded = function(mesh2) {
};
CollisionCoordinatorLegacy2.prototype.onMeshUpdated = function(mesh2) {
};
CollisionCoordinatorLegacy2.prototype.onMeshRemoved = function(mesh2) {
};
CollisionCoordinatorLegacy2.prototype.onGeometryAdded = function(geometry) {
};
CollisionCoordinatorLegacy2.prototype.onGeometryUpdated = function(geometry) {
};
CollisionCoordinatorLegacy2.prototype.onGeometryDeleted = function(geometry) {
};
CollisionCoordinatorLegacy2.prototype._collideWithWorld = function(position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
if (excludedMesh === void 0) {
excludedMesh = null;
}
var closeDistance = BABYLON2.Engine.CollisionsEpsilon * 10;
if (collider._retry >= maximumRetry) {
finalPosition.copyFrom(position);
return;
}
var collisionMask = excludedMesh ? excludedMesh.collisionMask : collider.collisionMask;
collider._initialize(position, velocity, closeDistance);
for (var index = 0; index < this._scene.meshes.length; index++) {
var mesh2 = this._scene.meshes[index];
if (mesh2.isEnabled() && mesh2.checkCollisions && mesh2.subMeshes && mesh2 !== excludedMesh && (collisionMask & mesh2.collisionGroup) !== 0) {
mesh2._checkCollision(collider);
}
}
if (!collider.collisionFound) {
position.addToRef(velocity, finalPosition);
return;
}
if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
collider._getResponse(position, velocity);
}
if (velocity.length() <= closeDistance) {
finalPosition.copyFrom(position);
return;
}
collider._retry++;
this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
};
return CollisionCoordinatorLegacy2;
}()
);
BABYLON2.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Particle = (
/** @class */
function() {
function Particle2(particleSystem) {
this.particleSystem = particleSystem;
this.position = BABYLON2.Vector3.Zero();
this.direction = BABYLON2.Vector3.Zero();
this.color = new BABYLON2.Color4(0, 0, 0, 0);
this.colorStep = new BABYLON2.Color4(0, 0, 0, 0);
this.lifeTime = 1;
this.age = 0;
this.size = 0;
this.scale = new BABYLON2.Vector2(1, 1);
this.angle = 0;
this.angularSpeed = 0;
this.cellIndex = 0;
this._attachedSubEmitters = null;
this._currentColor1 = new BABYLON2.Color4(0, 0, 0, 0);
this._currentColor2 = new BABYLON2.Color4(0, 0, 0, 0);
this._currentSize1 = 0;
this._currentSize2 = 0;
this._currentAngularSpeed1 = 0;
this._currentAngularSpeed2 = 0;
this._currentVelocity1 = 0;
this._currentVelocity2 = 0;
this._currentLimitVelocity1 = 0;
this._currentLimitVelocity2 = 0;
this._currentDrag1 = 0;
this._currentDrag2 = 0;
this.id = Particle2._Count++;
if (!this.particleSystem.isAnimationSheetEnabled) {
return;
}
this.updateCellInfoFromSystem();
}
Particle2.prototype.updateCellInfoFromSystem = function() {
this.cellIndex = this.particleSystem.startSpriteCellID;
};
Particle2.prototype.updateCellIndex = function() {
var offsetAge = this.age;
var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
if (this.particleSystem.spriteRandomStartCell) {
if (this._randomCellOffset === void 0) {
this._randomCellOffset = Math.random() * this.lifeTime;
}
if (changeSpeed === 0) {
changeSpeed = 1;
offsetAge = this._randomCellOffset;
} else {
offsetAge += this._randomCellOffset;
}
}
var dist = this._initialEndSpriteCellID - this._initialStartSpriteCellID;
var ratio = BABYLON2.Scalar.Clamp(offsetAge * changeSpeed % this.lifeTime / this.lifeTime);
this.cellIndex = this._initialStartSpriteCellID + ratio * dist | 0;
};
Particle2.prototype._inheritParticleInfoToSubEmitter = function(subEmitter) {
if (subEmitter.particleSystem.emitter.position) {
var emitterMesh = subEmitter.particleSystem.emitter;
emitterMesh.position.copyFrom(this.position);
if (subEmitter.inheritDirection) {
emitterMesh.position.subtractToRef(this.direction, BABYLON2.Tmp.Vector3[0]);
emitterMesh.lookAt(BABYLON2.Tmp.Vector3[0], 0, Math.PI / 2);
}
} else {
var emitterPosition = subEmitter.particleSystem.emitter;
emitterPosition.copyFrom(this.position);
}
this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON2.Tmp.Vector3[0]);
subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON2.Tmp.Vector3[0]);
};
Particle2.prototype._inheritParticleInfoToSubEmitters = function() {
var _this = this;
if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
this._attachedSubEmitters.forEach(function(subEmitter) {
_this._inheritParticleInfoToSubEmitter(subEmitter);
});
}
};
Particle2.prototype._reset = function() {
this.age = 0;
this._currentColorGradient = null;
this._currentSizeGradient = null;
this._currentAngularSpeedGradient = null;
this._currentVelocityGradient = null;
this._currentLimitVelocityGradient = null;
this._currentDragGradient = null;
this.cellIndex = this.particleSystem.startSpriteCellID;
this._randomCellOffset = void 0;
};
Particle2.prototype.copyTo = function(other) {
other.position.copyFrom(this.position);
if (this._initialDirection) {
if (other._initialDirection) {
other._initialDirection.copyFrom(this._initialDirection);
} else {
other._initialDirection = this._initialDirection.clone();
}
} else {
other._initialDirection = null;
}
other.direction.copyFrom(this.direction);
other.color.copyFrom(this.color);
other.colorStep.copyFrom(this.colorStep);
other.lifeTime = this.lifeTime;
other.age = this.age;
other._randomCellOffset = this._randomCellOffset;
other.size = this.size;
other.scale.copyFrom(this.scale);
other.angle = this.angle;
other.angularSpeed = this.angularSpeed;
other.particleSystem = this.particleSystem;
other.cellIndex = this.cellIndex;
other.id = this.id;
other._attachedSubEmitters = this._attachedSubEmitters;
if (this._currentColorGradient) {
other._currentColorGradient = this._currentColorGradient;
other._currentColor1.copyFrom(this._currentColor1);
other._currentColor2.copyFrom(this._currentColor2);
}
if (this._currentSizeGradient) {
other._currentSizeGradient = this._currentSizeGradient;
other._currentSize1 = this._currentSize1;
other._currentSize2 = this._currentSize2;
}
if (this._currentAngularSpeedGradient) {
other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
other._currentAngularSpeed1 = this._currentAngularSpeed1;
other._currentAngularSpeed2 = this._currentAngularSpeed2;
}
if (this._currentVelocityGradient) {
other._currentVelocityGradient = this._currentVelocityGradient;
other._currentVelocity1 = this._currentVelocity1;
other._currentVelocity2 = this._currentVelocity2;
}
if (this._currentLimitVelocityGradient) {
other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
other._currentLimitVelocity1 = this._currentLimitVelocity1;
other._currentLimitVelocity2 = this._currentLimitVelocity2;
}
if (this._currentDragGradient) {
other._currentDragGradient = this._currentDragGradient;
other._currentDrag1 = this._currentDrag1;
other._currentDrag2 = this._currentDrag2;
}
if (this.particleSystem.isAnimationSheetEnabled) {
other._initialStartSpriteCellID = this._initialStartSpriteCellID;
other._initialEndSpriteCellID = this._initialEndSpriteCellID;
}
if (this.particleSystem.useRampGradients) {
other.remapData.copyFrom(this.remapData);
}
if (this._randomNoiseCoordinates1) {
if (other._randomNoiseCoordinates1) {
other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
} else {
other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
}
}
};
Particle2._Count = 0;
return Particle2;
}()
);
BABYLON2.Particle = Particle;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BaseParticleSystem = (
/** @class */
function() {
function BaseParticleSystem2(name) {
this.animations = [];
this.renderingGroupId = 0;
this.emitter = null;
this.emitRate = 10;
this.manualEmitCount = -1;
this.updateSpeed = 0.01;
this.targetStopDuration = 0;
this.disposeOnStop = false;
this.minEmitPower = 1;
this.maxEmitPower = 1;
this.minLifeTime = 1;
this.maxLifeTime = 1;
this.minSize = 1;
this.maxSize = 1;
this.minScaleX = 1;
this.maxScaleX = 1;
this.minScaleY = 1;
this.maxScaleY = 1;
this.minInitialRotation = 0;
this.maxInitialRotation = 0;
this.minAngularSpeed = 0;
this.maxAngularSpeed = 0;
this.layerMask = 268435455;
this.customShader = null;
this.preventAutoStart = false;
this.noiseStrength = new BABYLON2.Vector3(10, 10, 10);
this.onAnimationEnd = null;
this.blendMode = BABYLON2.ParticleSystem.BLENDMODE_ONEONE;
this.forceDepthWrite = false;
this.preWarmCycles = 0;
this.preWarmStepOffset = 1;
this.spriteCellChangeSpeed = 1;
this.startSpriteCellID = 0;
this.endSpriteCellID = 0;
this.spriteCellWidth = 0;
this.spriteCellHeight = 0;
this.spriteRandomStartCell = false;
this.translationPivot = new BABYLON2.Vector2(0, 0);
this.beginAnimationOnStart = false;
this.beginAnimationFrom = 0;
this.beginAnimationTo = 60;
this.beginAnimationLoop = false;
this.gravity = BABYLON2.Vector3.Zero();
this._colorGradients = null;
this._sizeGradients = null;
this._lifeTimeGradients = null;
this._angularSpeedGradients = null;
this._velocityGradients = null;
this._limitVelocityGradients = null;
this._dragGradients = null;
this._emitRateGradients = null;
this._startSizeGradients = null;
this._rampGradients = null;
this._colorRemapGradients = null;
this._alphaRemapGradients = null;
this.startDelay = 0;
this.limitVelocityDamping = 0.4;
this.color1 = new BABYLON2.Color4(1, 1, 1, 1);
this.color2 = new BABYLON2.Color4(1, 1, 1, 1);
this.colorDead = new BABYLON2.Color4(0, 0, 0, 1);
this.textureMask = new BABYLON2.Color4(1, 1, 1, 1);
this._isSubEmitter = false;
this.billboardMode = BABYLON2.ParticleSystem.BILLBOARDMODE_ALL;
this._isBillboardBased = true;
this._imageProcessingConfigurationDefines = new BABYLON2.ImageProcessingConfigurationDefines();
this.id = name;
this.name = name;
}
Object.defineProperty(BaseParticleSystem2.prototype, "isAnimationSheetEnabled", {
/**
* Gets or sets whether an animation sprite sheet is enabled or not on the particle system
*/
get: function() {
return this._isAnimationSheetEnabled;
},
set: function(value) {
if (this._isAnimationSheetEnabled == value) {
return;
}
this._isAnimationSheetEnabled = value;
this._reset();
},
enumerable: true,
configurable: true
});
BaseParticleSystem2.prototype.getScene = function() {
return this._scene;
};
BaseParticleSystem2.prototype._hasTargetStopDurationDependantGradient = function() {
return this._startSizeGradients && this._startSizeGradients.length > 0 || this._emitRateGradients && this._emitRateGradients.length > 0 || this._lifeTimeGradients && this._lifeTimeGradients.length > 0;
};
BaseParticleSystem2.prototype.getDragGradients = function() {
return this._dragGradients;
};
BaseParticleSystem2.prototype.getLimitVelocityGradients = function() {
return this._limitVelocityGradients;
};
BaseParticleSystem2.prototype.getColorGradients = function() {
return this._colorGradients;
};
BaseParticleSystem2.prototype.getSizeGradients = function() {
return this._sizeGradients;
};
BaseParticleSystem2.prototype.getColorRemapGradients = function() {
return this._colorRemapGradients;
};
BaseParticleSystem2.prototype.getAlphaRemapGradients = function() {
return this._alphaRemapGradients;
};
BaseParticleSystem2.prototype.getLifeTimeGradients = function() {
return this._lifeTimeGradients;
};
BaseParticleSystem2.prototype.getAngularSpeedGradients = function() {
return this._angularSpeedGradients;
};
BaseParticleSystem2.prototype.getVelocityGradients = function() {
return this._velocityGradients;
};
BaseParticleSystem2.prototype.getStartSizeGradients = function() {
return this._startSizeGradients;
};
BaseParticleSystem2.prototype.getEmitRateGradients = function() {
return this._emitRateGradients;
};
Object.defineProperty(BaseParticleSystem2.prototype, "direction1", {
/**
* Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
* This only works when particleEmitterTyps is a BoxParticleEmitter
*/
get: function() {
if (this.particleEmitterType.direction1) {
return this.particleEmitterType.direction1;
}
return BABYLON2.Vector3.Zero();
},
set: function(value) {
if (this.particleEmitterType.direction1) {
this.particleEmitterType.direction1 = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseParticleSystem2.prototype, "direction2", {
/**
* Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
* This only works when particleEmitterTyps is a BoxParticleEmitter
*/
get: function() {
if (this.particleEmitterType.direction2) {
return this.particleEmitterType.direction2;
}
return BABYLON2.Vector3.Zero();
},
set: function(value) {
if (this.particleEmitterType.direction2) {
this.particleEmitterType.direction2 = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseParticleSystem2.prototype, "minEmitBox", {
/**
* Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
* This only works when particleEmitterTyps is a BoxParticleEmitter
*/
get: function() {
if (this.particleEmitterType.minEmitBox) {
return this.particleEmitterType.minEmitBox;
}
return BABYLON2.Vector3.Zero();
},
set: function(value) {
if (this.particleEmitterType.minEmitBox) {
this.particleEmitterType.minEmitBox = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseParticleSystem2.prototype, "maxEmitBox", {
/**
* Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
* This only works when particleEmitterTyps is a BoxParticleEmitter
*/
get: function() {
if (this.particleEmitterType.maxEmitBox) {
return this.particleEmitterType.maxEmitBox;
}
return BABYLON2.Vector3.Zero();
},
set: function(value) {
if (this.particleEmitterType.maxEmitBox) {
this.particleEmitterType.maxEmitBox = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseParticleSystem2.prototype, "isBillboardBased", {
/**
* Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
*/
get: function() {
return this._isBillboardBased;
},
set: function(value) {
if (this._isBillboardBased === value) {
return;
}
this._isBillboardBased = value;
this._reset();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseParticleSystem2.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function() {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function(value) {
this._attachImageProcessingConfiguration(value);
},
enumerable: true,
configurable: true
});
BaseParticleSystem2.prototype._attachImageProcessingConfiguration = function(configuration) {
if (configuration === this._imageProcessingConfiguration) {
return;
}
if (!configuration) {
this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
} else {
this._imageProcessingConfiguration = configuration;
}
};
BaseParticleSystem2.prototype._reset = function() {
};
BaseParticleSystem2.prototype._removeGradientAndTexture = function(gradient, gradients, texture) {
if (!gradients) {
return this;
}
var index = 0;
for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
var valueGradient = gradients_1[_i];
if (valueGradient.gradient === gradient) {
gradients.splice(index, 1);
break;
}
index++;
}
if (texture) {
texture.dispose();
}
return this;
};
BaseParticleSystem2.prototype.createPointEmitter = function(direction1, direction2) {
var particleEmitter = new BABYLON2.PointParticleEmitter();
particleEmitter.direction1 = direction1;
particleEmitter.direction2 = direction2;
this.particleEmitterType = particleEmitter;
return particleEmitter;
};
BaseParticleSystem2.prototype.createHemisphericEmitter = function(radius, radiusRange) {
if (radius === void 0) {
radius = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
var particleEmitter = new BABYLON2.HemisphericParticleEmitter(radius, radiusRange);
this.particleEmitterType = particleEmitter;
return particleEmitter;
};
BaseParticleSystem2.prototype.createSphereEmitter = function(radius, radiusRange) {
if (radius === void 0) {
radius = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
var particleEmitter = new BABYLON2.SphereParticleEmitter(radius, radiusRange);
this.particleEmitterType = particleEmitter;
return particleEmitter;
};
BaseParticleSystem2.prototype.createDirectedSphereEmitter = function(radius, direction1, direction2) {
if (radius === void 0) {
radius = 1;
}
if (direction1 === void 0) {
direction1 = new BABYLON2.Vector3(0, 1, 0);
}
if (direction2 === void 0) {
direction2 = new BABYLON2.Vector3(0, 1, 0);
}
var particleEmitter = new BABYLON2.SphereDirectedParticleEmitter(radius, direction1, direction2);
this.particleEmitterType = particleEmitter;
return particleEmitter;
};
BaseParticleSystem2.prototype.createCylinderEmitter = function(radius, height, radiusRange, directionRandomizer) {
if (radius === void 0) {
radius = 1;
}
if (height === void 0) {
height = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
if (directionRandomizer === void 0) {
directionRandomizer = 0;
}
var particleEmitter = new BABYLON2.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
this.particleEmitterType = particleEmitter;
return particleEmitter;
};
BaseParticleSystem2.prototype.createDirectedCylinderEmitter = function(radius, height, radiusRange, direction1, direction2) {
if (radius === void 0) {
radius = 1;
}
if (height === void 0) {
height = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
if (direction1 === void 0) {
direction1 = new BABYLON2.Vector3(0, 1, 0);
}
if (direction2 === void 0) {
direction2 = new BABYLON2.Vector3(0, 1, 0);
}
var particleEmitter = new BABYLON2.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
this.particleEmitterType = particleEmitter;
return particleEmitter;
};
BaseParticleSystem2.prototype.createConeEmitter = function(radius, angle) {
if (radius === void 0) {
radius = 1;
}
if (angle === void 0) {
angle = Math.PI / 4;
}
var particleEmitter = new BABYLON2.ConeParticleEmitter(radius, angle);
this.particleEmitterType = particleEmitter;
return particleEmitter;
};
BaseParticleSystem2.prototype.createBoxEmitter = function(direction1, direction2, minEmitBox, maxEmitBox) {
var particleEmitter = new BABYLON2.BoxParticleEmitter();
this.particleEmitterType = particleEmitter;
this.direction1 = direction1;
this.direction2 = direction2;
this.minEmitBox = minEmitBox;
this.maxEmitBox = maxEmitBox;
return particleEmitter;
};
BaseParticleSystem2.BLENDMODE_ONEONE = 0;
BaseParticleSystem2.BLENDMODE_STANDARD = 1;
BaseParticleSystem2.BLENDMODE_ADD = 2;
BaseParticleSystem2.BLENDMODE_MULTIPLY = 3;
BaseParticleSystem2.BLENDMODE_MULTIPLYADD = 4;
return BaseParticleSystem2;
}()
);
BABYLON2.BaseParticleSystem = BaseParticleSystem;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ParticleSystem = (
/** @class */
function(_super) {
__extends(ParticleSystem2, _super);
function ParticleSystem2(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
if (customEffect === void 0) {
customEffect = null;
}
if (isAnimationSheetEnabled === void 0) {
isAnimationSheetEnabled = false;
}
if (epsilon === void 0) {
epsilon = 0.01;
}
var _this = _super.call(this, name) || this;
_this._inheritedVelocityOffset = new BABYLON2.Vector3();
_this.onDisposeObservable = new BABYLON2.Observable();
_this._particles = new Array();
_this._stockParticles = new Array();
_this._newPartsExcess = 0;
_this._vertexBuffers = {};
_this._scaledColorStep = new BABYLON2.Color4(0, 0, 0, 0);
_this._colorDiff = new BABYLON2.Color4(0, 0, 0, 0);
_this._scaledDirection = BABYLON2.Vector3.Zero();
_this._scaledGravity = BABYLON2.Vector3.Zero();
_this._currentRenderId = -1;
_this._useInstancing = false;
_this._started = false;
_this._stopped = false;
_this._actualFrame = 0;
_this._currentEmitRate1 = 0;
_this._currentEmitRate2 = 0;
_this._currentStartSize1 = 0;
_this._currentStartSize2 = 0;
_this._rawTextureWidth = 256;
_this._useRampGradients = false;
_this._disposeEmitterOnDispose = false;
_this.recycleParticle = function(particle) {
var lastParticle = _this._particles.pop();
if (lastParticle !== particle) {
lastParticle.copyTo(particle);
}
_this._stockParticles.push(lastParticle);
};
_this._createParticle = function() {
var particle;
if (_this._stockParticles.length !== 0) {
particle = _this._stockParticles.pop();
particle._reset();
} else {
particle = new BABYLON2.Particle(_this);
}
if (_this._subEmitters && _this._subEmitters.length > 0) {
var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
particle._attachedSubEmitters = [];
subEmitters.forEach(function(subEmitter) {
if (subEmitter.type === BABYLON2.SubEmitterType.ATTACHED) {
var newEmitter = subEmitter.clone();
particle._attachedSubEmitters.push(newEmitter);
newEmitter.particleSystem.start();
}
});
}
return particle;
};
_this._emitFromParticle = function(particle) {
if (!_this._subEmitters || _this._subEmitters.length === 0) {
return;
}
var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
_this._subEmitters[templateIndex].forEach(function(subEmitter) {
if (subEmitter.type === BABYLON2.SubEmitterType.END) {
var subSystem = subEmitter.clone();
particle._inheritParticleInfoToSubEmitter(subSystem);
subSystem.particleSystem._rootParticleSystem = _this;
_this.activeSubSystems.push(subSystem.particleSystem);
subSystem.particleSystem.start();
}
});
};
_this._capacity = capacity;
_this._epsilon = epsilon;
_this._isAnimationSheetEnabled = isAnimationSheetEnabled;
_this._scene = scene || BABYLON2.Engine.LastCreatedScene;
_this._attachImageProcessingConfiguration(null);
_this._customEffect = customEffect;
_this._scene.particleSystems.push(_this);
_this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
_this._createIndexBuffer();
_this._createVertexBuffers();
_this.particleEmitterType = new BABYLON2.BoxParticleEmitter();
_this.updateFunction = function(particles) {
var noiseTextureSize = null;
var noiseTextureData = null;
if (_this.noiseTexture) {
noiseTextureSize = _this.noiseTexture.getSize();
noiseTextureData = _this.noiseTexture.getContent();
}
var _loop_1 = function() {
particle = particles[index];
var scaledUpdateSpeed = _this._scaledUpdateSpeed;
var previousAge = particle.age;
particle.age += scaledUpdateSpeed;
if (particle.age > particle.lifeTime) {
var diff = particle.age - previousAge;
var oldDiff = particle.lifeTime - previousAge;
scaledUpdateSpeed = oldDiff * scaledUpdateSpeed / diff;
particle.age = particle.lifeTime;
}
var ratio = particle.age / particle.lifeTime;
if (_this._colorGradients && _this._colorGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._colorGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== particle._currentColorGradient) {
particle._currentColor1.copyFrom(particle._currentColor2);
nextGradient.getColorToRef(particle._currentColor2);
particle._currentColorGradient = currentGradient;
}
BABYLON2.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
});
} else {
particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
particle.color.addInPlace(_this._scaledColorStep);
if (particle.color.a < 0) {
particle.color.a = 0;
}
}
if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== particle._currentAngularSpeedGradient) {
particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
particle._currentAngularSpeed2 = nextGradient.getFactor();
particle._currentAngularSpeedGradient = currentGradient;
}
particle.angularSpeed = BABYLON2.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
});
}
particle.angle += particle.angularSpeed * scaledUpdateSpeed;
var directionScale = scaledUpdateSpeed;
if (_this._velocityGradients && _this._velocityGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== particle._currentVelocityGradient) {
particle._currentVelocity1 = particle._currentVelocity2;
particle._currentVelocity2 = nextGradient.getFactor();
particle._currentVelocityGradient = currentGradient;
}
directionScale *= BABYLON2.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
});
}
particle.direction.scaleToRef(directionScale, _this._scaledDirection);
if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== particle._currentLimitVelocityGradient) {
particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
particle._currentLimitVelocity2 = nextGradient.getFactor();
particle._currentLimitVelocityGradient = currentGradient;
}
var limitVelocity = BABYLON2.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
var currentVelocity = particle.direction.length();
if (currentVelocity > limitVelocity) {
particle.direction.scaleInPlace(_this.limitVelocityDamping);
}
});
}
if (_this._dragGradients && _this._dragGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._dragGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== particle._currentDragGradient) {
particle._currentDrag1 = particle._currentDrag2;
particle._currentDrag2 = nextGradient.getFactor();
particle._currentDragGradient = currentGradient;
}
var drag = BABYLON2.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
_this._scaledDirection.scaleInPlace(1 - drag);
});
}
particle.position.addInPlace(_this._scaledDirection);
if (noiseTextureData && noiseTextureSize) {
var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
var force = BABYLON2.Tmp.Vector3[0];
var scaledForce = BABYLON2.Tmp.Vector3[1];
force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
force.scaleToRef(scaledUpdateSpeed, scaledForce);
particle.direction.addInPlace(scaledForce);
}
_this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
particle.direction.addInPlace(_this._scaledGravity);
if (_this._sizeGradients && _this._sizeGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== particle._currentSizeGradient) {
particle._currentSize1 = particle._currentSize2;
particle._currentSize2 = nextGradient.getFactor();
particle._currentSizeGradient = currentGradient;
}
particle.size = BABYLON2.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
});
}
if (_this._useRampGradients) {
if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function(currentGradient, nextGradient, scale) {
var min = BABYLON2.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
var max = BABYLON2.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
particle.remapData.x = min;
particle.remapData.y = max - min;
});
}
if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
BABYLON2.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function(currentGradient, nextGradient, scale) {
var min = BABYLON2.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
var max = BABYLON2.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
particle.remapData.z = min;
particle.remapData.w = max - min;
});
}
}
if (_this._isAnimationSheetEnabled) {
particle.updateCellIndex();
}
particle._inheritParticleInfoToSubEmitters();
if (particle.age >= particle.lifeTime) {
_this._emitFromParticle(particle);
if (particle._attachedSubEmitters) {
particle._attachedSubEmitters.forEach(function(subEmitter) {
subEmitter.particleSystem.disposeOnStop = true;
subEmitter.particleSystem.stop();
});
particle._attachedSubEmitters = null;
}
_this.recycleParticle(particle);
index--;
return "continue";
}
};
var particle;
for (var index = 0; index < particles.length; index++) {
_loop_1();
}
};
return _this;
}
Object.defineProperty(ParticleSystem2.prototype, "onDispose", {
/**
* Sets a callback that will be triggered when the system is disposed
*/
set: function(callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ParticleSystem2.prototype, "useRampGradients", {
/** Gets or sets a boolean indicating that ramp gradients must be used
* @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
*/
get: function() {
return this._useRampGradients;
},
set: function(value) {
if (this._useRampGradients === value) {
return;
}
this._useRampGradients = value;
this._resetEffect();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ParticleSystem2.prototype, "particles", {
//end of Sub-emitter
/**
* Gets the current list of active particles
*/
get: function() {
return this._particles;
},
enumerable: true,
configurable: true
});
ParticleSystem2.prototype.getClassName = function() {
return "ParticleSystem";
};
ParticleSystem2.prototype._addFactorGradient = function(factorGradients, gradient, factor, factor2) {
var newGradient = new BABYLON2.FactorGradient();
newGradient.gradient = gradient;
newGradient.factor1 = factor;
newGradient.factor2 = factor2;
factorGradients.push(newGradient);
factorGradients.sort(function(a, b2) {
if (a.gradient < b2.gradient) {
return -1;
} else if (a.gradient > b2.gradient) {
return 1;
}
return 0;
});
};
ParticleSystem2.prototype._removeFactorGradient = function(factorGradients, gradient) {
if (!factorGradients) {
return;
}
var index = 0;
for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
var factorGradient = factorGradients_1[_i];
if (factorGradient.gradient === gradient) {
factorGradients.splice(index, 1);
break;
}
index++;
}
};
ParticleSystem2.prototype.addLifeTimeGradient = function(gradient, factor, factor2) {
if (!this._lifeTimeGradients) {
this._lifeTimeGradients = [];
}
this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeLifeTimeGradient = function(gradient) {
this._removeFactorGradient(this._lifeTimeGradients, gradient);
return this;
};
ParticleSystem2.prototype.addSizeGradient = function(gradient, factor, factor2) {
if (!this._sizeGradients) {
this._sizeGradients = [];
}
this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeSizeGradient = function(gradient) {
this._removeFactorGradient(this._sizeGradients, gradient);
return this;
};
ParticleSystem2.prototype.addColorRemapGradient = function(gradient, min, max) {
if (!this._colorRemapGradients) {
this._colorRemapGradients = [];
}
this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
return this;
};
ParticleSystem2.prototype.removeColorRemapGradient = function(gradient) {
this._removeFactorGradient(this._colorRemapGradients, gradient);
return this;
};
ParticleSystem2.prototype.addAlphaRemapGradient = function(gradient, min, max) {
if (!this._alphaRemapGradients) {
this._alphaRemapGradients = [];
}
this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
return this;
};
ParticleSystem2.prototype.removeAlphaRemapGradient = function(gradient) {
this._removeFactorGradient(this._alphaRemapGradients, gradient);
return this;
};
ParticleSystem2.prototype.addAngularSpeedGradient = function(gradient, factor, factor2) {
if (!this._angularSpeedGradients) {
this._angularSpeedGradients = [];
}
this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeAngularSpeedGradient = function(gradient) {
this._removeFactorGradient(this._angularSpeedGradients, gradient);
return this;
};
ParticleSystem2.prototype.addVelocityGradient = function(gradient, factor, factor2) {
if (!this._velocityGradients) {
this._velocityGradients = [];
}
this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeVelocityGradient = function(gradient) {
this._removeFactorGradient(this._velocityGradients, gradient);
return this;
};
ParticleSystem2.prototype.addLimitVelocityGradient = function(gradient, factor, factor2) {
if (!this._limitVelocityGradients) {
this._limitVelocityGradients = [];
}
this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeLimitVelocityGradient = function(gradient) {
this._removeFactorGradient(this._limitVelocityGradients, gradient);
return this;
};
ParticleSystem2.prototype.addDragGradient = function(gradient, factor, factor2) {
if (!this._dragGradients) {
this._dragGradients = [];
}
this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeDragGradient = function(gradient) {
this._removeFactorGradient(this._dragGradients, gradient);
return this;
};
ParticleSystem2.prototype.addEmitRateGradient = function(gradient, factor, factor2) {
if (!this._emitRateGradients) {
this._emitRateGradients = [];
}
this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeEmitRateGradient = function(gradient) {
this._removeFactorGradient(this._emitRateGradients, gradient);
return this;
};
ParticleSystem2.prototype.addStartSizeGradient = function(gradient, factor, factor2) {
if (!this._startSizeGradients) {
this._startSizeGradients = [];
}
this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
return this;
};
ParticleSystem2.prototype.removeStartSizeGradient = function(gradient) {
this._removeFactorGradient(this._emitRateGradients, gradient);
return this;
};
ParticleSystem2.prototype._createRampGradientTexture = function() {
if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
return;
}
var data2 = new Uint8Array(this._rawTextureWidth * 4);
var tmpColor = BABYLON2.Tmp.Color3[0];
for (var x = 0; x < this._rawTextureWidth; x++) {
var ratio = x / this._rawTextureWidth;
BABYLON2.Tools.GetCurrentGradient(ratio, this._rampGradients, function(currentGradient, nextGradient, scale) {
BABYLON2.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
data2[x * 4] = tmpColor.r * 255;
data2[x * 4 + 1] = tmpColor.g * 255;
data2[x * 4 + 2] = tmpColor.b * 255;
data2[x * 4 + 3] = 255;
});
}
this._rampGradientsTexture = BABYLON2.RawTexture.CreateRGBATexture(data2, this._rawTextureWidth, 1, this._scene, false, false, BABYLON2.Texture.NEAREST_SAMPLINGMODE);
};
ParticleSystem2.prototype.getRampGradients = function() {
return this._rampGradients;
};
ParticleSystem2.prototype.addRampGradient = function(gradient, color) {
if (!this._rampGradients) {
this._rampGradients = [];
}
var rampGradient = new BABYLON2.Color3Gradient();
rampGradient.gradient = gradient;
rampGradient.color = color;
this._rampGradients.push(rampGradient);
this._rampGradients.sort(function(a, b2) {
if (a.gradient < b2.gradient) {
return -1;
} else if (a.gradient > b2.gradient) {
return 1;
}
return 0;
});
if (this._rampGradientsTexture) {
this._rampGradientsTexture.dispose();
this._rampGradientsTexture = null;
}
this._createRampGradientTexture();
return this;
};
ParticleSystem2.prototype.removeRampGradient = function(gradient) {
this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
this._rampGradientsTexture = null;
if (this._rampGradients && this._rampGradients.length > 0) {
this._createRampGradientTexture();
}
return this;
};
ParticleSystem2.prototype.addColorGradient = function(gradient, color1, color2) {
if (!this._colorGradients) {
this._colorGradients = [];
}
var colorGradient = new BABYLON2.ColorGradient();
colorGradient.gradient = gradient;
colorGradient.color1 = color1;
colorGradient.color2 = color2;
this._colorGradients.push(colorGradient);
this._colorGradients.sort(function(a, b2) {
if (a.gradient < b2.gradient) {
return -1;
} else if (a.gradient > b2.gradient) {
return 1;
}
return 0;
});
return this;
};
ParticleSystem2.prototype.removeColorGradient = function(gradient) {
if (!this._colorGradients) {
return this;
}
var index = 0;
for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
var colorGradient = _a[_i];
if (colorGradient.gradient === gradient) {
this._colorGradients.splice(index, 1);
break;
}
index++;
}
return this;
};
ParticleSystem2.prototype._fetchR = function(u, v, width, height, pixels) {
u = Math.abs(u) * 0.5 + 0.5;
v = Math.abs(v) * 0.5 + 0.5;
var wrappedU = u * width % width | 0;
var wrappedV = v * height % height | 0;
var position = (wrappedU + wrappedV * width) * 4;
return pixels[position] / 255;
};
ParticleSystem2.prototype._reset = function() {
this._resetEffect();
};
ParticleSystem2.prototype._resetEffect = function() {
if (this._vertexBuffer) {
this._vertexBuffer.dispose();
this._vertexBuffer = null;
}
if (this._spriteBuffer) {
this._spriteBuffer.dispose();
this._spriteBuffer = null;
}
this._createVertexBuffers();
};
ParticleSystem2.prototype._createVertexBuffers = function() {
this._vertexBufferSize = this._useInstancing ? 10 : 12;
if (this._isAnimationSheetEnabled) {
this._vertexBufferSize += 1;
}
if (!this._isBillboardBased || this.billboardMode === ParticleSystem2.BILLBOARDMODE_STRETCHED) {
this._vertexBufferSize += 3;
}
if (this._useRampGradients) {
this._vertexBufferSize += 4;
}
var engine = this._scene.getEngine();
this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
this._vertexBuffer = new BABYLON2.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
var dataOffset = 0;
var positions = this._vertexBuffer.createVertexBuffer(BABYLON2.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = positions;
dataOffset += 3;
var colors = this._vertexBuffer.createVertexBuffer(BABYLON2.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
this._vertexBuffers[BABYLON2.VertexBuffer.ColorKind] = colors;
dataOffset += 4;
var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
this._vertexBuffers["angle"] = options;
dataOffset += 1;
var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
this._vertexBuffers["size"] = size;
dataOffset += 2;
if (this._isAnimationSheetEnabled) {
var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
this._vertexBuffers["cellIndex"] = cellIndexBuffer;
dataOffset += 1;
}
if (!this._isBillboardBased || this.billboardMode === ParticleSystem2.BILLBOARDMODE_STRETCHED) {
var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
this._vertexBuffers["direction"] = directionBuffer;
dataOffset += 3;
}
if (this._useRampGradients) {
var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
this._vertexBuffers["remapData"] = rampDataBuffer;
dataOffset += 4;
}
var offsets;
if (this._useInstancing) {
var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
this._spriteBuffer = new BABYLON2.Buffer(engine, spriteData, false, 2);
offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
} else {
offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
dataOffset += 2;
}
this._vertexBuffers["offset"] = offsets;
};
ParticleSystem2.prototype._createIndexBuffer = function() {
if (this._useInstancing) {
return;
}
var indices = [];
var index = 0;
for (var count = 0; count < this._capacity; count++) {
indices.push(index);
indices.push(index + 1);
indices.push(index + 2);
indices.push(index);
indices.push(index + 2);
indices.push(index + 3);
index += 4;
}
this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
};
ParticleSystem2.prototype.getCapacity = function() {
return this._capacity;
};
ParticleSystem2.prototype.isAlive = function() {
return this._alive;
};
ParticleSystem2.prototype.isStarted = function() {
return this._started;
};
ParticleSystem2.prototype._prepareSubEmitterInternalArray = function() {
var _this = this;
this._subEmitters = new Array();
if (this.subEmitters) {
this.subEmitters.forEach(function(subEmitter) {
if (subEmitter instanceof ParticleSystem2) {
_this._subEmitters.push([new BABYLON2.SubEmitter(subEmitter)]);
} else if (subEmitter instanceof BABYLON2.SubEmitter) {
_this._subEmitters.push([subEmitter]);
} else if (subEmitter instanceof Array) {
_this._subEmitters.push(subEmitter);
}
});
}
};
ParticleSystem2.prototype.start = function(delay) {
var _this = this;
if (delay === void 0) {
delay = this.startDelay;
}
if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
}
if (delay) {
setTimeout(function() {
_this.start(0);
}, delay);
return;
}
this._prepareSubEmitterInternalArray();
this._started = true;
this._stopped = false;
this._actualFrame = 0;
if (this._subEmitters && this._subEmitters.length != 0) {
this.activeSubSystems = new Array();
}
if (this._emitRateGradients) {
if (this._emitRateGradients.length > 0) {
this._currentEmitRateGradient = this._emitRateGradients[0];
this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
this._currentEmitRate2 = this._currentEmitRate1;
}
if (this._emitRateGradients.length > 1) {
this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
}
}
if (this._startSizeGradients) {
if (this._startSizeGradients.length > 0) {
this._currentStartSizeGradient = this._startSizeGradients[0];
this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
this._currentStartSize2 = this._currentStartSize1;
}
if (this._startSizeGradients.length > 1) {
this._currentStartSize2 = this._startSizeGradients[1].getFactor();
}
}
if (this.preWarmCycles) {
if (this.emitter instanceof BABYLON2.AbstractMesh) {
this.emitter.computeWorldMatrix(true);
}
var noiseTextureAsProcedural_1 = this.noiseTexture;
if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function() {
setTimeout(function() {
for (var index2 = 0; index2 < _this.preWarmCycles; index2++) {
_this.animate(true);
noiseTextureAsProcedural_1.render();
}
});
});
} else {
for (var index = 0; index < this.preWarmCycles; index++) {
this.animate(true);
}
}
}
if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
}
};
ParticleSystem2.prototype.stop = function(stopSubEmitters) {
if (stopSubEmitters === void 0) {
stopSubEmitters = true;
}
this._stopped = true;
if (stopSubEmitters) {
this._stopSubEmitters();
}
};
ParticleSystem2.prototype.reset = function() {
this._stockParticles = [];
this._particles = [];
};
ParticleSystem2.prototype._appendParticleVertex = function(index, particle, offsetX, offsetY) {
var offset = index * this._vertexBufferSize;
this._vertexData[offset++] = particle.position.x;
this._vertexData[offset++] = particle.position.y;
this._vertexData[offset++] = particle.position.z;
this._vertexData[offset++] = particle.color.r;
this._vertexData[offset++] = particle.color.g;
this._vertexData[offset++] = particle.color.b;
this._vertexData[offset++] = particle.color.a;
this._vertexData[offset++] = particle.angle;
this._vertexData[offset++] = particle.scale.x * particle.size;
this._vertexData[offset++] = particle.scale.y * particle.size;
if (this._isAnimationSheetEnabled) {
this._vertexData[offset++] = particle.cellIndex;
}
if (!this._isBillboardBased) {
if (particle._initialDirection) {
this._vertexData[offset++] = particle._initialDirection.x;
this._vertexData[offset++] = particle._initialDirection.y;
this._vertexData[offset++] = particle._initialDirection.z;
} else {
this._vertexData[offset++] = particle.direction.x;
this._vertexData[offset++] = particle.direction.y;
this._vertexData[offset++] = particle.direction.z;
}
} else if (this.billboardMode === ParticleSystem2.BILLBOARDMODE_STRETCHED) {
this._vertexData[offset++] = particle.direction.x;
this._vertexData[offset++] = particle.direction.y;
this._vertexData[offset++] = particle.direction.z;
}
if (this._useRampGradients) {
this._vertexData[offset++] = particle.remapData.x;
this._vertexData[offset++] = particle.remapData.y;
this._vertexData[offset++] = particle.remapData.z;
this._vertexData[offset++] = particle.remapData.w;
}
if (!this._useInstancing) {
if (this._isAnimationSheetEnabled) {
if (offsetX === 0) {
offsetX = this._epsilon;
} else if (offsetX === 1) {
offsetX = 1 - this._epsilon;
}
if (offsetY === 0) {
offsetY = this._epsilon;
} else if (offsetY === 1) {
offsetY = 1 - this._epsilon;
}
}
this._vertexData[offset++] = offsetX;
this._vertexData[offset++] = offsetY;
}
};
ParticleSystem2.prototype._stopSubEmitters = function() {
if (!this.activeSubSystems) {
return;
}
this.activeSubSystems.forEach(function(subSystem) {
subSystem.stop(true);
});
this.activeSubSystems = new Array();
};
ParticleSystem2.prototype._removeFromRoot = function() {
if (!this._rootParticleSystem) {
return;
}
var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
if (index !== -1) {
this._rootParticleSystem.activeSubSystems.splice(index, 1);
}
this._rootParticleSystem = null;
};
ParticleSystem2.prototype._update = function(newParticles) {
var _this = this;
this._alive = this._particles.length > 0;
if (this.emitter.position) {
var emitterMesh = this.emitter;
this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
} else {
var emitterPosition = this.emitter;
this._emitterWorldMatrix = BABYLON2.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
}
this.updateFunction(this._particles);
var particle;
var _loop_2 = function() {
if (this_1._particles.length === this_1._capacity) {
return "break";
}
particle = this_1._createParticle();
this_1._particles.push(particle);
var emitPower = BABYLON2.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
if (this_1.startPositionFunction) {
this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
} else {
this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
}
if (this_1.startDirectionFunction) {
this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
} else {
this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
}
if (emitPower === 0) {
if (!particle._initialDirection) {
particle._initialDirection = particle.direction.clone();
} else {
particle._initialDirection.copyFrom(particle.direction);
}
} else {
particle._initialDirection = null;
}
particle.direction.scaleInPlace(emitPower);
if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
var ratio_1 = BABYLON2.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
BABYLON2.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function(currentGradient, nextGradient, scale) {
var factorGradient1 = currentGradient;
var factorGradient2 = nextGradient;
var lifeTime1 = factorGradient1.getFactor();
var lifeTime2 = factorGradient2.getFactor();
var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
particle.lifeTime = BABYLON2.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
});
} else {
particle.lifeTime = BABYLON2.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
}
if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
particle.size = BABYLON2.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
} else {
particle._currentSizeGradient = this_1._sizeGradients[0];
particle._currentSize1 = particle._currentSizeGradient.getFactor();
particle.size = particle._currentSize1;
if (this_1._sizeGradients.length > 1) {
particle._currentSize2 = this_1._sizeGradients[1].getFactor();
} else {
particle._currentSize2 = particle._currentSize1;
}
}
particle.scale.copyFromFloats(BABYLON2.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON2.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
var ratio = this_1._actualFrame / this_1.targetStopDuration;
BABYLON2.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== _this._currentStartSizeGradient) {
_this._currentStartSize1 = _this._currentStartSize2;
_this._currentStartSize2 = nextGradient.getFactor();
_this._currentStartSizeGradient = currentGradient;
}
var value = BABYLON2.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
particle.scale.scaleInPlace(value);
});
}
if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
particle.angularSpeed = BABYLON2.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
} else {
particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
particle._currentAngularSpeed1 = particle.angularSpeed;
if (this_1._angularSpeedGradients.length > 1) {
particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
} else {
particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
}
}
particle.angle = BABYLON2.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
particle._currentVelocityGradient = this_1._velocityGradients[0];
particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
if (this_1._velocityGradients.length > 1) {
particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
} else {
particle._currentVelocity2 = particle._currentVelocity1;
}
}
if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
if (this_1._limitVelocityGradients.length > 1) {
particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
} else {
particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
}
}
if (this_1._dragGradients && this_1._dragGradients.length > 0) {
particle._currentDragGradient = this_1._dragGradients[0];
particle._currentDrag1 = particle._currentDragGradient.getFactor();
if (this_1._dragGradients.length > 1) {
particle._currentDrag2 = this_1._dragGradients[1].getFactor();
} else {
particle._currentDrag2 = particle._currentDrag1;
}
}
if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
step = BABYLON2.Scalar.RandomRange(0, 1);
BABYLON2.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
this_1._colorDiff.scaleToRef(1 / particle.lifeTime, particle.colorStep);
} else {
particle._currentColorGradient = this_1._colorGradients[0];
particle._currentColorGradient.getColorToRef(particle.color);
particle._currentColor1.copyFrom(particle.color);
if (this_1._colorGradients.length > 1) {
this_1._colorGradients[1].getColorToRef(particle._currentColor2);
} else {
particle._currentColor2.copyFrom(particle.color);
}
}
if (this_1._isAnimationSheetEnabled) {
particle._initialStartSpriteCellID = this_1.startSpriteCellID;
particle._initialEndSpriteCellID = this_1.endSpriteCellID;
}
particle.direction.addInPlace(this_1._inheritedVelocityOffset);
if (this_1._useRampGradients) {
particle.remapData = new BABYLON2.Vector4(0, 1, 0, 1);
}
if (this_1.noiseTexture) {
if (particle._randomNoiseCoordinates1) {
particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
} else {
particle._randomNoiseCoordinates1 = new BABYLON2.Vector3(Math.random(), Math.random(), Math.random());
particle._randomNoiseCoordinates2 = new BABYLON2.Vector3(Math.random(), Math.random(), Math.random());
}
}
particle._inheritParticleInfoToSubEmitters();
};
var this_1 = this, step;
for (var index = 0; index < newParticles; index++) {
var state_1 = _loop_2();
if (state_1 === "break")
break;
}
};
ParticleSystem2._GetAttributeNamesOrOptions = function(isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
if (isAnimationSheetEnabled === void 0) {
isAnimationSheetEnabled = false;
}
if (isBillboardBased === void 0) {
isBillboardBased = false;
}
if (useRampGradients === void 0) {
useRampGradients = false;
}
var attributeNamesOrOptions = [BABYLON2.VertexBuffer.PositionKind, BABYLON2.VertexBuffer.ColorKind, "angle", "offset", "size"];
if (isAnimationSheetEnabled) {
attributeNamesOrOptions.push("cellIndex");
}
if (!isBillboardBased) {
attributeNamesOrOptions.push("direction");
}
if (useRampGradients) {
attributeNamesOrOptions.push("remapData");
}
return attributeNamesOrOptions;
};
ParticleSystem2._GetEffectCreationOptions = function(isAnimationSheetEnabled) {
if (isAnimationSheetEnabled === void 0) {
isAnimationSheetEnabled = false;
}
var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
if (isAnimationSheetEnabled) {
effectCreationOption.push("particlesInfos");
}
return effectCreationOption;
};
ParticleSystem2.prototype._getEffect = function(blendMode) {
if (this._customEffect) {
return this._customEffect;
}
var defines = [];
if (this._scene.clipPlane) {
defines.push("#define CLIPPLANE");
}
if (this._scene.clipPlane2) {
defines.push("#define CLIPPLANE2");
}
if (this._scene.clipPlane3) {
defines.push("#define CLIPPLANE3");
}
if (this._scene.clipPlane4) {
defines.push("#define CLIPPLANE4");
}
if (this._isAnimationSheetEnabled) {
defines.push("#define ANIMATESHEET");
}
if (blendMode === ParticleSystem2.BLENDMODE_MULTIPLY) {
defines.push("#define BLENDMULTIPLYMODE");
}
if (this._useRampGradients) {
defines.push("#define RAMPGRADIENT");
}
if (this._isBillboardBased) {
defines.push("#define BILLBOARD");
switch (this.billboardMode) {
case ParticleSystem2.BILLBOARDMODE_Y:
defines.push("#define BILLBOARDY");
break;
case ParticleSystem2.BILLBOARDMODE_STRETCHED:
defines.push("#define BILLBOARDSTRETCHED");
break;
case ParticleSystem2.BILLBOARDMODE_ALL:
default:
break;
}
}
if (this._imageProcessingConfiguration) {
this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
defines.push(this._imageProcessingConfigurationDefines.toString());
}
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
var attributesNamesOrOptions = ParticleSystem2._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem2.BILLBOARDMODE_STRETCHED, this._useRampGradients);
var effectCreationOption = ParticleSystem2._GetEffectCreationOptions(this._isAnimationSheetEnabled);
var samplers = ["diffuseSampler", "rampSampler"];
if (BABYLON2.ImageProcessingConfiguration) {
BABYLON2.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
BABYLON2.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
}
this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
}
return this._effect;
};
ParticleSystem2.prototype.animate = function(preWarmOnly) {
var _this = this;
if (preWarmOnly === void 0) {
preWarmOnly = false;
}
if (!this._started) {
return;
}
if (!preWarmOnly) {
if (!this.isReady()) {
return;
}
if (this._currentRenderId === this._scene.getRenderId()) {
return;
}
this._currentRenderId = this._scene.getRenderId();
}
this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
var newParticles;
if (this.manualEmitCount > -1) {
newParticles = this.manualEmitCount;
this._newPartsExcess = 0;
this.manualEmitCount = 0;
} else {
var rate_1 = this.emitRate;
if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
var ratio = this._actualFrame / this.targetStopDuration;
BABYLON2.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function(currentGradient, nextGradient, scale) {
if (currentGradient !== _this._currentEmitRateGradient) {
_this._currentEmitRate1 = _this._currentEmitRate2;
_this._currentEmitRate2 = nextGradient.getFactor();
_this._currentEmitRateGradient = currentGradient;
}
rate_1 = BABYLON2.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
});
}
newParticles = rate_1 * this._scaledUpdateSpeed >> 0;
this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
}
if (this._newPartsExcess > 1) {
newParticles += this._newPartsExcess >> 0;
this._newPartsExcess -= this._newPartsExcess >> 0;
}
this._alive = false;
if (!this._stopped) {
this._actualFrame += this._scaledUpdateSpeed;
if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
this.stop();
}
} else {
newParticles = 0;
}
this._update(newParticles);
if (this._stopped) {
if (!this._alive) {
this._started = false;
if (this.onAnimationEnd) {
this.onAnimationEnd();
}
if (this.disposeOnStop) {
this._scene._toBeDisposed.push(this);
}
}
}
if (!preWarmOnly) {
var offset = 0;
for (var index = 0; index < this._particles.length; index++) {
var particle = this._particles[index];
this._appendParticleVertices(offset, particle);
offset += this._useInstancing ? 1 : 4;
}
if (this._vertexBuffer) {
this._vertexBuffer.update(this._vertexData);
}
}
if (this.manualEmitCount === 0 && this.disposeOnStop) {
this.stop();
}
};
ParticleSystem2.prototype._appendParticleVertices = function(offset, particle) {
this._appendParticleVertex(offset++, particle, 0, 0);
if (!this._useInstancing) {
this._appendParticleVertex(offset++, particle, 1, 0);
this._appendParticleVertex(offset++, particle, 1, 1);
this._appendParticleVertex(offset++, particle, 0, 1);
}
};
ParticleSystem2.prototype.rebuild = function() {
this._createIndexBuffer();
if (this._vertexBuffer) {
this._vertexBuffer._rebuild();
}
};
ParticleSystem2.prototype.isReady = function() {
if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
return false;
}
if (this.blendMode !== ParticleSystem2.BLENDMODE_MULTIPLYADD) {
if (!this._getEffect(this.blendMode).isReady()) {
return false;
}
} else {
if (!this._getEffect(ParticleSystem2.BLENDMODE_MULTIPLY).isReady()) {
return false;
}
if (!this._getEffect(ParticleSystem2.BLENDMODE_ADD).isReady()) {
return false;
}
}
return true;
};
ParticleSystem2.prototype._render = function(blendMode) {
var effect = this._getEffect(blendMode);
var engine = this._scene.getEngine();
engine.enableEffect(effect);
var viewMatrix = this._scene.getViewMatrix();
effect.setTexture("diffuseSampler", this.particleTexture);
effect.setMatrix("view", viewMatrix);
effect.setMatrix("projection", this._scene.getProjectionMatrix());
if (this._isAnimationSheetEnabled && this.particleTexture) {
var baseSize = this.particleTexture.getBaseSize();
effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
}
effect.setVector2("translationPivot", this.translationPivot);
effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
if (this._isBillboardBased) {
var camera2 = this._scene.activeCamera;
effect.setVector3("eyePosition", camera2.globalPosition);
}
if (this._rampGradientsTexture) {
effect.setTexture("rampSampler", this._rampGradientsTexture);
}
if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
var invView = viewMatrix.clone();
invView.invert();
effect.setMatrix("invView", invView);
BABYLON2.MaterialHelper.BindClipPlane(effect, this._scene);
}
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
this._imageProcessingConfiguration.bind(effect);
}
switch (blendMode) {
case ParticleSystem2.BLENDMODE_ADD:
engine.setAlphaMode(BABYLON2.Engine.ALPHA_ADD);
break;
case ParticleSystem2.BLENDMODE_ONEONE:
engine.setAlphaMode(BABYLON2.Engine.ALPHA_ONEONE);
break;
case ParticleSystem2.BLENDMODE_STANDARD:
engine.setAlphaMode(BABYLON2.Engine.ALPHA_COMBINE);
break;
case ParticleSystem2.BLENDMODE_MULTIPLY:
engine.setAlphaMode(BABYLON2.Engine.ALPHA_MULTIPLY);
break;
}
if (this._useInstancing) {
engine.drawArraysType(BABYLON2.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
} else {
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, this._particles.length * 6);
}
return this._particles.length;
};
ParticleSystem2.prototype.render = function() {
if (!this.isReady() || !this._particles.length) {
return 0;
}
var engine = this._scene.getEngine();
engine.setState(false);
if (this.forceDepthWrite) {
engine.setDepthWrite(true);
}
var outparticles = 0;
if (this.blendMode === ParticleSystem2.BLENDMODE_MULTIPLYADD) {
outparticles = this._render(ParticleSystem2.BLENDMODE_MULTIPLY) + this._render(ParticleSystem2.BLENDMODE_ADD);
}
outparticles = this._render(this.blendMode);
engine.unbindInstanceAttributes();
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
return outparticles;
};
ParticleSystem2.prototype.dispose = function(disposeTexture) {
if (disposeTexture === void 0) {
disposeTexture = true;
}
if (this._vertexBuffer) {
this._vertexBuffer.dispose();
this._vertexBuffer = null;
}
if (this._spriteBuffer) {
this._spriteBuffer.dispose();
this._spriteBuffer = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
if (disposeTexture && this.particleTexture) {
this.particleTexture.dispose();
this.particleTexture = null;
}
if (disposeTexture && this.noiseTexture) {
this.noiseTexture.dispose();
this.noiseTexture = null;
}
if (this._rampGradientsTexture) {
this._rampGradientsTexture.dispose();
this._rampGradientsTexture = null;
}
this._removeFromRoot();
if (this._subEmitters && this._subEmitters.length) {
for (var index = 0; index < this._subEmitters.length; index++) {
for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
var subEmitter = _a[_i];
subEmitter.dispose();
}
}
this._subEmitters = [];
this.subEmitters = [];
}
if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
this.emitter.dispose(true);
}
var index = this._scene.particleSystems.indexOf(this);
if (index > -1) {
this._scene.particleSystems.splice(index, 1);
}
this._scene._activeParticleSystems.dispose();
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.reset();
};
ParticleSystem2.prototype.clone = function(name, newEmitter) {
var custom = null;
var program = null;
if (this.customShader != null) {
program = this.customShader;
var defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : "";
custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
} else if (this._customEffect) {
custom = this._customEffect;
}
var result = new ParticleSystem2(name, this._capacity, this._scene, custom);
result.customShader = program;
BABYLON2.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
if (newEmitter === void 0) {
newEmitter = this.emitter;
}
result.noiseTexture = this.noiseTexture;
result.emitter = newEmitter;
if (this.particleTexture) {
result.particleTexture = new BABYLON2.Texture(this.particleTexture.url, this._scene);
}
if (this._colorGradients) {
this._colorGradients.forEach(function(v) {
result.addColorGradient(v.gradient, v.color1, v.color2);
});
}
if (this._dragGradients) {
this._dragGradients.forEach(function(v) {
result.addDragGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._angularSpeedGradients) {
this._angularSpeedGradients.forEach(function(v) {
result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._emitRateGradients) {
this._emitRateGradients.forEach(function(v) {
result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._lifeTimeGradients) {
this._lifeTimeGradients.forEach(function(v) {
result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._limitVelocityGradients) {
this._limitVelocityGradients.forEach(function(v) {
result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._sizeGradients) {
this._sizeGradients.forEach(function(v) {
result.addSizeGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._startSizeGradients) {
this._startSizeGradients.forEach(function(v) {
result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._velocityGradients) {
this._velocityGradients.forEach(function(v) {
result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._rampGradients) {
this._rampGradients.forEach(function(v) {
result.addRampGradient(v.gradient, v.color);
});
}
if (this._colorRemapGradients) {
this._colorRemapGradients.forEach(function(v) {
result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
});
}
if (this._alphaRemapGradients) {
this._alphaRemapGradients.forEach(function(v) {
result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
});
}
if (!this.preventAutoStart) {
result.start();
}
return result;
};
ParticleSystem2.prototype.serialize = function() {
var serializationObject = {};
ParticleSystem2._Serialize(serializationObject, this);
serializationObject.textureMask = this.textureMask.asArray();
serializationObject.customShader = this.customShader;
serializationObject.preventAutoStart = this.preventAutoStart;
if (this.subEmitters) {
serializationObject.subEmitters = [];
if (!this._subEmitters) {
this._prepareSubEmitterInternalArray();
}
for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
var subs = _a[_i];
var cell = [];
for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
var sub = subs_1[_b];
cell.push(sub.serialize());
}
serializationObject.subEmitters.push(cell);
}
}
return serializationObject;
};
ParticleSystem2._Serialize = function(serializationObject, particleSystem) {
serializationObject.name = particleSystem.name;
serializationObject.id = particleSystem.id;
serializationObject.capacity = particleSystem.getCapacity();
if (particleSystem.emitter.position) {
var emitterMesh = particleSystem.emitter;
serializationObject.emitterId = emitterMesh.id;
} else {
var emitterPosition = particleSystem.emitter;
serializationObject.emitter = emitterPosition.asArray();
}
if (particleSystem.particleEmitterType) {
serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
}
if (particleSystem.particleTexture) {
serializationObject.textureName = particleSystem.particleTexture.name;
serializationObject.invertY = particleSystem.particleTexture._invertY;
}
BABYLON2.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
serializationObject.startDelay = particleSystem.startDelay;
serializationObject.renderingGroupId = particleSystem.renderingGroupId;
serializationObject.isBillboardBased = particleSystem.isBillboardBased;
serializationObject.billboardMode = particleSystem.billboardMode;
serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
serializationObject.minSize = particleSystem.minSize;
serializationObject.maxSize = particleSystem.maxSize;
serializationObject.minScaleX = particleSystem.minScaleX;
serializationObject.maxScaleX = particleSystem.maxScaleX;
serializationObject.minScaleY = particleSystem.minScaleY;
serializationObject.maxScaleY = particleSystem.maxScaleY;
serializationObject.minEmitPower = particleSystem.minEmitPower;
serializationObject.maxEmitPower = particleSystem.maxEmitPower;
serializationObject.minLifeTime = particleSystem.minLifeTime;
serializationObject.maxLifeTime = particleSystem.maxLifeTime;
serializationObject.emitRate = particleSystem.emitRate;
serializationObject.gravity = particleSystem.gravity.asArray();
serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
serializationObject.color1 = particleSystem.color1.asArray();
serializationObject.color2 = particleSystem.color2.asArray();
serializationObject.colorDead = particleSystem.colorDead.asArray();
serializationObject.updateSpeed = particleSystem.updateSpeed;
serializationObject.targetStopDuration = particleSystem.targetStopDuration;
serializationObject.blendMode = particleSystem.blendMode;
serializationObject.preWarmCycles = particleSystem.preWarmCycles;
serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
serializationObject.minInitialRotation = particleSystem.minInitialRotation;
serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
var colorGradients = particleSystem.getColorGradients();
if (colorGradients) {
serializationObject.colorGradients = [];
for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
var colorGradient = colorGradients_1[_i];
var serializedGradient = {
gradient: colorGradient.gradient,
color1: colorGradient.color1.asArray()
};
if (colorGradient.color2) {
serializedGradient.color2 = colorGradient.color2.asArray();
}
serializationObject.colorGradients.push(serializedGradient);
}
}
var rampGradients = particleSystem.getRampGradients();
if (rampGradients) {
serializationObject.rampGradients = [];
for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
var rampGradient = rampGradients_1[_a];
var serializedGradient = {
gradient: rampGradient.gradient,
color: rampGradient.color.asArray()
};
serializationObject.rampGradients.push(serializedGradient);
}
serializationObject.useRampGradients = particleSystem.useRampGradients;
}
var colorRemapGradients = particleSystem.getColorRemapGradients();
if (colorRemapGradients) {
serializationObject.colorRemapGradients = [];
for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
var colorRemapGradient = colorRemapGradients_1[_b];
var serializedGradient = {
gradient: colorRemapGradient.gradient,
factor1: colorRemapGradient.factor1
};
if (colorRemapGradient.factor2 !== void 0) {
serializedGradient.factor2 = colorRemapGradient.factor2;
}
serializationObject.colorRemapGradients.push(serializedGradient);
}
}
var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
if (alphaRemapGradients) {
serializationObject.alphaRemapGradients = [];
for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
var alphaRemapGradient = alphaRemapGradients_1[_c];
var serializedGradient = {
gradient: alphaRemapGradient.gradient,
factor1: alphaRemapGradient.factor1
};
if (alphaRemapGradient.factor2 !== void 0) {
serializedGradient.factor2 = alphaRemapGradient.factor2;
}
serializationObject.alphaRemapGradients.push(serializedGradient);
}
}
var sizeGradients = particleSystem.getSizeGradients();
if (sizeGradients) {
serializationObject.sizeGradients = [];
for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
var sizeGradient = sizeGradients_1[_d];
var serializedGradient = {
gradient: sizeGradient.gradient,
factor1: sizeGradient.factor1
};
if (sizeGradient.factor2 !== void 0) {
serializedGradient.factor2 = sizeGradient.factor2;
}
serializationObject.sizeGradients.push(serializedGradient);
}
}
var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
if (angularSpeedGradients) {
serializationObject.angularSpeedGradients = [];
for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
var angularSpeedGradient = angularSpeedGradients_1[_e];
var serializedGradient = {
gradient: angularSpeedGradient.gradient,
factor1: angularSpeedGradient.factor1
};
if (angularSpeedGradient.factor2 !== void 0) {
serializedGradient.factor2 = angularSpeedGradient.factor2;
}
serializationObject.angularSpeedGradients.push(serializedGradient);
}
}
var velocityGradients = particleSystem.getVelocityGradients();
if (velocityGradients) {
serializationObject.velocityGradients = [];
for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
var velocityGradient = velocityGradients_1[_f];
var serializedGradient = {
gradient: velocityGradient.gradient,
factor1: velocityGradient.factor1
};
if (velocityGradient.factor2 !== void 0) {
serializedGradient.factor2 = velocityGradient.factor2;
}
serializationObject.velocityGradients.push(serializedGradient);
}
}
var dragGradients = particleSystem.getDragGradients();
if (dragGradients) {
serializationObject.dragyGradients = [];
for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
var dragGradient = dragGradients_1[_g];
var serializedGradient = {
gradient: dragGradient.gradient,
factor1: dragGradient.factor1
};
if (dragGradient.factor2 !== void 0) {
serializedGradient.factor2 = dragGradient.factor2;
}
serializationObject.dragGradients.push(serializedGradient);
}
}
var emitRateGradients = particleSystem.getEmitRateGradients();
if (emitRateGradients) {
serializationObject.emitRateGradients = [];
for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
var emitRateGradient = emitRateGradients_1[_h];
var serializedGradient = {
gradient: emitRateGradient.gradient,
factor1: emitRateGradient.factor1
};
if (emitRateGradient.factor2 !== void 0) {
serializedGradient.factor2 = emitRateGradient.factor2;
}
serializationObject.emitRateGradients.push(serializedGradient);
}
}
var startSizeGradients = particleSystem.getStartSizeGradients();
if (startSizeGradients) {
serializationObject.startSizeGradients = [];
for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
var startSizeGradient = startSizeGradients_1[_j];
var serializedGradient = {
gradient: startSizeGradient.gradient,
factor1: startSizeGradient.factor1
};
if (startSizeGradient.factor2 !== void 0) {
serializedGradient.factor2 = startSizeGradient.factor2;
}
serializationObject.startSizeGradients.push(serializedGradient);
}
}
var lifeTimeGradients = particleSystem.getLifeTimeGradients();
if (lifeTimeGradients) {
serializationObject.lifeTimeGradients = [];
for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
var lifeTimeGradient = lifeTimeGradients_1[_k];
var serializedGradient = {
gradient: lifeTimeGradient.gradient,
factor1: lifeTimeGradient.factor1
};
if (lifeTimeGradient.factor2 !== void 0) {
serializedGradient.factor2 = lifeTimeGradient.factor2;
}
serializationObject.lifeTimeGradients.push(serializedGradient);
}
}
var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
if (limitVelocityGradients) {
serializationObject.limitVelocityGradients = [];
for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
var limitVelocityGradient = limitVelocityGradients_1[_l];
var serializedGradient = {
gradient: limitVelocityGradient.gradient,
factor1: limitVelocityGradient.factor1
};
if (limitVelocityGradient.factor2 !== void 0) {
serializedGradient.factor2 = limitVelocityGradient.factor2;
}
serializationObject.limitVelocityGradients.push(serializedGradient);
}
serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
}
if (particleSystem.noiseTexture) {
serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
}
};
ParticleSystem2._Parse = function(parsedParticleSystem, particleSystem, scene, rootUrl) {
if (parsedParticleSystem.textureName) {
particleSystem.particleTexture = new BABYLON2.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== void 0 ? parsedParticleSystem.invertY : true);
particleSystem.particleTexture.name = parsedParticleSystem.textureName;
}
if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === void 0) {
particleSystem.emitter = BABYLON2.Vector3.Zero();
} else if (parsedParticleSystem.emitterId) {
particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
} else {
particleSystem.emitter = BABYLON2.Vector3.FromArray(parsedParticleSystem.emitter);
}
if (parsedParticleSystem.renderingGroupId !== void 0) {
particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
}
if (parsedParticleSystem.isBillboardBased !== void 0) {
particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
}
if (parsedParticleSystem.billboardMode !== void 0) {
particleSystem.billboardMode = parsedParticleSystem.billboardMode;
}
if (parsedParticleSystem.animations) {
for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
var parsedAnimation = parsedParticleSystem.animations[animationIndex];
particleSystem.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
}
if (parsedParticleSystem.autoAnimate) {
scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1);
}
particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
particleSystem.minSize = parsedParticleSystem.minSize;
particleSystem.maxSize = parsedParticleSystem.maxSize;
if (parsedParticleSystem.minScaleX) {
particleSystem.minScaleX = parsedParticleSystem.minScaleX;
particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
particleSystem.minScaleY = parsedParticleSystem.minScaleY;
particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
}
if (parsedParticleSystem.preWarmCycles !== void 0) {
particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
}
if (parsedParticleSystem.minInitialRotation !== void 0) {
particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
}
particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
particleSystem.emitRate = parsedParticleSystem.emitRate;
particleSystem.gravity = BABYLON2.Vector3.FromArray(parsedParticleSystem.gravity);
if (parsedParticleSystem.noiseStrength) {
particleSystem.noiseStrength = BABYLON2.Vector3.FromArray(parsedParticleSystem.noiseStrength);
}
particleSystem.color1 = BABYLON2.Color4.FromArray(parsedParticleSystem.color1);
particleSystem.color2 = BABYLON2.Color4.FromArray(parsedParticleSystem.color2);
particleSystem.colorDead = BABYLON2.Color4.FromArray(parsedParticleSystem.colorDead);
particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
particleSystem.blendMode = parsedParticleSystem.blendMode;
if (parsedParticleSystem.colorGradients) {
for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
var colorGradient = _a[_i];
particleSystem.addColorGradient(colorGradient.gradient, BABYLON2.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON2.Color4.FromArray(colorGradient.color2) : void 0);
}
}
if (parsedParticleSystem.rampGradients) {
for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
var rampGradient = _c[_b];
particleSystem.addRampGradient(rampGradient.gradient, BABYLON2.Color3.FromArray(rampGradient.color));
}
particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
}
if (parsedParticleSystem.colorRemapGradients) {
for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
var colorRemapGradient = _e[_d];
particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== void 0 ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
}
}
if (parsedParticleSystem.alphaRemapGradients) {
for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
var alphaRemapGradient = _g[_f];
particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== void 0 ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
}
}
if (parsedParticleSystem.sizeGradients) {
for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
var sizeGradient = _j[_h];
particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== void 0 ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
}
}
if (parsedParticleSystem.sizeGradients) {
for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
var sizeGradient = _l[_k];
particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== void 0 ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
}
}
if (parsedParticleSystem.angularSpeedGradients) {
for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
var angularSpeedGradient = _o[_m];
particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== void 0 ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
}
}
if (parsedParticleSystem.velocityGradients) {
for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
var velocityGradient = _q[_p];
particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== void 0 ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
}
}
if (parsedParticleSystem.dragGradients) {
for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
var dragGradient = _s[_r];
particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== void 0 ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
}
}
if (parsedParticleSystem.emitRateGradients) {
for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
var emitRateGradient = _u[_t];
particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== void 0 ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
}
}
if (parsedParticleSystem.startSizeGradients) {
for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
var startSizeGradient = _w[_v];
particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== void 0 ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
}
}
if (parsedParticleSystem.lifeTimeGradients) {
for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
var lifeTimeGradient = _y[_x];
particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== void 0 ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
}
}
if (parsedParticleSystem.limitVelocityGradients) {
for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
var limitVelocityGradient = _0[_z];
particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== void 0 ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
}
particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
}
if (parsedParticleSystem.noiseTexture) {
particleSystem.noiseTexture = BABYLON2.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
}
var emitterType;
if (parsedParticleSystem.particleEmitterType) {
switch (parsedParticleSystem.particleEmitterType.type) {
case "SphereParticleEmitter":
emitterType = new BABYLON2.SphereParticleEmitter();
break;
case "SphereDirectedParticleEmitter":
emitterType = new BABYLON2.SphereDirectedParticleEmitter();
break;
case "ConeEmitter":
case "ConeParticleEmitter":
emitterType = new BABYLON2.ConeParticleEmitter();
break;
case "CylinderParticleEmitter":
emitterType = new BABYLON2.CylinderParticleEmitter();
break;
case "HemisphericParticleEmitter":
emitterType = new BABYLON2.HemisphericParticleEmitter();
break;
case "BoxEmitter":
case "BoxParticleEmitter":
default:
emitterType = new BABYLON2.BoxParticleEmitter();
break;
}
emitterType.parse(parsedParticleSystem.particleEmitterType);
} else {
emitterType = new BABYLON2.BoxParticleEmitter();
emitterType.parse(parsedParticleSystem);
}
particleSystem.particleEmitterType = emitterType;
particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
};
ParticleSystem2.Parse = function(parsedParticleSystem, scene, rootUrl, doNotStart) {
if (doNotStart === void 0) {
doNotStart = false;
}
var name = parsedParticleSystem.name;
var custom = null;
var program = null;
if (parsedParticleSystem.customShader) {
program = parsedParticleSystem.customShader;
var defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : "";
custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
}
var particleSystem = new ParticleSystem2(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
particleSystem.customShader = program;
if (parsedParticleSystem.id) {
particleSystem.id = parsedParticleSystem.id;
}
if (parsedParticleSystem.subEmitters) {
particleSystem.subEmitters = [];
for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
var cell = _a[_i];
var cellArray = [];
for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
var sub = cell_1[_b];
cellArray.push(BABYLON2.SubEmitter.Parse(sub, scene, rootUrl));
}
particleSystem.subEmitters.push(cellArray);
}
}
ParticleSystem2._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
particleSystem.textureMask = BABYLON2.Color4.FromArray(parsedParticleSystem.textureMask);
if (parsedParticleSystem.preventAutoStart) {
particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
}
if (!doNotStart && !particleSystem.preventAutoStart) {
particleSystem.start();
}
return particleSystem;
};
ParticleSystem2.BILLBOARDMODE_Y = 2;
ParticleSystem2.BILLBOARDMODE_ALL = 7;
ParticleSystem2.BILLBOARDMODE_STRETCHED = 8;
return ParticleSystem2;
}(BABYLON2.BaseParticleSystem)
);
BABYLON2.ParticleSystem = ParticleSystem;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BoxParticleEmitter = (
/** @class */
function() {
function BoxParticleEmitter2() {
this.direction1 = new BABYLON2.Vector3(0, 1, 0);
this.direction2 = new BABYLON2.Vector3(0, 1, 0);
this.minEmitBox = new BABYLON2.Vector3(-0.5, -0.5, -0.5);
this.maxEmitBox = new BABYLON2.Vector3(0.5, 0.5, 0.5);
}
BoxParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
var randX = BABYLON2.Scalar.RandomRange(this.direction1.x, this.direction2.x);
var randY = BABYLON2.Scalar.RandomRange(this.direction1.y, this.direction2.y);
var randZ = BABYLON2.Scalar.RandomRange(this.direction1.z, this.direction2.z);
BABYLON2.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
};
BoxParticleEmitter2.prototype.startPositionFunction = function(worldMatrix, positionToUpdate, particle) {
var randX = BABYLON2.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
var randY = BABYLON2.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
var randZ = BABYLON2.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
};
BoxParticleEmitter2.prototype.clone = function() {
var newOne = new BoxParticleEmitter2();
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
BoxParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setVector3("direction1", this.direction1);
effect.setVector3("direction2", this.direction2);
effect.setVector3("minEmitBox", this.minEmitBox);
effect.setVector3("maxEmitBox", this.maxEmitBox);
};
BoxParticleEmitter2.prototype.getEffectDefines = function() {
return "#define BOXEMITTER";
};
BoxParticleEmitter2.prototype.getClassName = function() {
return "BoxParticleEmitter";
};
BoxParticleEmitter2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.type = this.getClassName();
serializationObject.direction1 = this.direction1.asArray();
serializationObject.direction2 = this.direction2.asArray();
serializationObject.minEmitBox = this.minEmitBox.asArray();
serializationObject.maxEmitBox = this.maxEmitBox.asArray();
return serializationObject;
};
BoxParticleEmitter2.prototype.parse = function(serializationObject) {
BABYLON2.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
BABYLON2.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
BABYLON2.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
BABYLON2.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
};
return BoxParticleEmitter2;
}()
);
BABYLON2.BoxParticleEmitter = BoxParticleEmitter;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var CylinderParticleEmitter = (
/** @class */
function() {
function CylinderParticleEmitter2(radius, height, radiusRange, directionRandomizer) {
if (radius === void 0) {
radius = 1;
}
if (height === void 0) {
height = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
if (directionRandomizer === void 0) {
directionRandomizer = 0;
}
this.radius = radius;
this.height = height;
this.radiusRange = radiusRange;
this.directionRandomizer = directionRandomizer;
}
CylinderParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
var randY = BABYLON2.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
var angle = Math.atan2(direction.x, direction.z);
angle += BABYLON2.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
direction.y = randY;
direction.x = Math.sin(angle);
direction.z = Math.cos(angle);
direction.normalize();
BABYLON2.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
};
CylinderParticleEmitter2.prototype.startPositionFunction = function(worldMatrix, positionToUpdate, particle) {
var yPos = BABYLON2.Scalar.RandomRange(-this.height / 2, this.height / 2);
var angle = BABYLON2.Scalar.RandomRange(0, 2 * Math.PI);
var radiusDistribution = BABYLON2.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
var xPos = positionRadius * Math.cos(angle);
var zPos = positionRadius * Math.sin(angle);
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
};
CylinderParticleEmitter2.prototype.clone = function() {
var newOne = new CylinderParticleEmitter2(this.radius, this.directionRandomizer);
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
CylinderParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setFloat("radius", this.radius);
effect.setFloat("height", this.height);
effect.setFloat("radiusRange", this.radiusRange);
effect.setFloat("directionRandomizer", this.directionRandomizer);
};
CylinderParticleEmitter2.prototype.getEffectDefines = function() {
return "#define CYLINDEREMITTER";
};
CylinderParticleEmitter2.prototype.getClassName = function() {
return "CylinderParticleEmitter";
};
CylinderParticleEmitter2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.type = this.getClassName();
serializationObject.radius = this.radius;
serializationObject.height = this.height;
serializationObject.radiusRange = this.radiusRange;
serializationObject.directionRandomizer = this.directionRandomizer;
return serializationObject;
};
CylinderParticleEmitter2.prototype.parse = function(serializationObject) {
this.radius = serializationObject.radius;
this.height = serializationObject.height;
this.radiusRange = serializationObject.radiusRange;
this.directionRandomizer = serializationObject.directionRandomizer;
};
return CylinderParticleEmitter2;
}()
);
BABYLON2.CylinderParticleEmitter = CylinderParticleEmitter;
var CylinderDirectedParticleEmitter = (
/** @class */
function(_super) {
__extends(CylinderDirectedParticleEmitter2, _super);
function CylinderDirectedParticleEmitter2(radius, height, radiusRange, direction1, direction2) {
if (radius === void 0) {
radius = 1;
}
if (height === void 0) {
height = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
if (direction1 === void 0) {
direction1 = new BABYLON2.Vector3(0, 1, 0);
}
if (direction2 === void 0) {
direction2 = new BABYLON2.Vector3(0, 1, 0);
}
var _this = _super.call(this, radius, height, radiusRange) || this;
_this.direction1 = direction1;
_this.direction2 = direction2;
return _this;
}
CylinderDirectedParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
var randX = BABYLON2.Scalar.RandomRange(this.direction1.x, this.direction2.x);
var randY = BABYLON2.Scalar.RandomRange(this.direction1.y, this.direction2.y);
var randZ = BABYLON2.Scalar.RandomRange(this.direction1.z, this.direction2.z);
BABYLON2.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
};
CylinderDirectedParticleEmitter2.prototype.clone = function() {
var newOne = new CylinderDirectedParticleEmitter2(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
CylinderDirectedParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setFloat("radius", this.radius);
effect.setFloat("height", this.height);
effect.setFloat("radiusRange", this.radiusRange);
effect.setVector3("direction1", this.direction1);
effect.setVector3("direction2", this.direction2);
};
CylinderDirectedParticleEmitter2.prototype.getEffectDefines = function() {
return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
};
CylinderDirectedParticleEmitter2.prototype.getClassName = function() {
return "CylinderDirectedParticleEmitter";
};
CylinderDirectedParticleEmitter2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.direction1 = this.direction1.asArray();
serializationObject.direction2 = this.direction2.asArray();
return serializationObject;
};
CylinderDirectedParticleEmitter2.prototype.parse = function(serializationObject) {
_super.prototype.parse.call(this, serializationObject);
this.direction1.copyFrom(serializationObject.direction1);
this.direction2.copyFrom(serializationObject.direction2);
};
return CylinderDirectedParticleEmitter2;
}(CylinderParticleEmitter)
);
BABYLON2.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ConeParticleEmitter = (
/** @class */
function() {
function ConeParticleEmitter2(radius, angle, directionRandomizer) {
if (radius === void 0) {
radius = 1;
}
if (angle === void 0) {
angle = Math.PI;
}
if (directionRandomizer === void 0) {
directionRandomizer = 0;
}
this.directionRandomizer = directionRandomizer;
this.radiusRange = 1;
this.heightRange = 1;
this.emitFromSpawnPointOnly = false;
this.angle = angle;
this.radius = radius;
}
Object.defineProperty(ConeParticleEmitter2.prototype, "radius", {
/**
* Gets or sets the radius of the emission cone
*/
get: function() {
return this._radius;
},
set: function(value) {
this._radius = value;
this._buildHeight();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConeParticleEmitter2.prototype, "angle", {
/**
* Gets or sets the angle of the emission cone
*/
get: function() {
return this._angle;
},
set: function(value) {
this._angle = value;
this._buildHeight();
},
enumerable: true,
configurable: true
});
ConeParticleEmitter2.prototype._buildHeight = function() {
if (this._angle !== 0) {
this._height = this._radius / Math.tan(this._angle / 2);
} else {
this._height = 1;
}
};
ConeParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
if (Math.abs(Math.cos(this._angle)) === 1) {
BABYLON2.Vector3.TransformNormalFromFloatsToRef(0, 1, 0, worldMatrix, directionToUpdate);
} else {
var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
var randX = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
var randY = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
var randZ = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
direction.x += randX;
direction.y += randY;
direction.z += randZ;
direction.normalize();
BABYLON2.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
}
};
ConeParticleEmitter2.prototype.startPositionFunction = function(worldMatrix, positionToUpdate, particle) {
var s = BABYLON2.Scalar.RandomRange(0, Math.PI * 2);
var h;
if (!this.emitFromSpawnPointOnly) {
h = BABYLON2.Scalar.RandomRange(0, this.heightRange);
h = 1 - h * h;
} else {
h = 1e-4;
}
var radius = this._radius - BABYLON2.Scalar.RandomRange(0, this._radius * this.radiusRange);
radius = radius * h;
var randX = radius * Math.sin(s);
var randZ = radius * Math.cos(s);
var randY = h * this._height;
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
};
ConeParticleEmitter2.prototype.clone = function() {
var newOne = new ConeParticleEmitter2(this._radius, this._angle, this.directionRandomizer);
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
ConeParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setFloat2("radius", this._radius, this.radiusRange);
effect.setFloat("coneAngle", this._angle);
effect.setFloat2("height", this._height, this.heightRange);
effect.setFloat("directionRandomizer", this.directionRandomizer);
};
ConeParticleEmitter2.prototype.getEffectDefines = function() {
var defines = "#define CONEEMITTER";
if (this.emitFromSpawnPointOnly) {
defines += "\n#define CONEEMITTERSPAWNPOINT";
}
return defines;
};
ConeParticleEmitter2.prototype.getClassName = function() {
return "ConeParticleEmitter";
};
ConeParticleEmitter2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.type = this.getClassName();
serializationObject.radius = this._radius;
serializationObject.angle = this._angle;
serializationObject.directionRandomizer = this.directionRandomizer;
return serializationObject;
};
ConeParticleEmitter2.prototype.parse = function(serializationObject) {
this.radius = serializationObject.radius;
this.angle = serializationObject.angle;
this.directionRandomizer = serializationObject.directionRandomizer;
};
return ConeParticleEmitter2;
}()
);
BABYLON2.ConeParticleEmitter = ConeParticleEmitter;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SphereParticleEmitter = (
/** @class */
function() {
function SphereParticleEmitter2(radius, radiusRange, directionRandomizer) {
if (radius === void 0) {
radius = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
if (directionRandomizer === void 0) {
directionRandomizer = 0;
}
this.radius = radius;
this.radiusRange = radiusRange;
this.directionRandomizer = directionRandomizer;
}
SphereParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
var randX = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
var randY = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
var randZ = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
direction.x += randX;
direction.y += randY;
direction.z += randZ;
direction.normalize();
BABYLON2.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
};
SphereParticleEmitter2.prototype.startPositionFunction = function(worldMatrix, positionToUpdate, particle) {
var randRadius = this.radius - BABYLON2.Scalar.RandomRange(0, this.radius * this.radiusRange);
var v = BABYLON2.Scalar.RandomRange(0, 1);
var phi = BABYLON2.Scalar.RandomRange(0, 2 * Math.PI);
var theta = Math.acos(2 * v - 1);
var randX = randRadius * Math.cos(phi) * Math.sin(theta);
var randY = randRadius * Math.cos(theta);
var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
};
SphereParticleEmitter2.prototype.clone = function() {
var newOne = new SphereParticleEmitter2(this.radius, this.directionRandomizer);
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
SphereParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setFloat("radius", this.radius);
effect.setFloat("radiusRange", this.radiusRange);
effect.setFloat("directionRandomizer", this.directionRandomizer);
};
SphereParticleEmitter2.prototype.getEffectDefines = function() {
return "#define SPHEREEMITTER";
};
SphereParticleEmitter2.prototype.getClassName = function() {
return "SphereParticleEmitter";
};
SphereParticleEmitter2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.type = this.getClassName();
serializationObject.radius = this.radius;
serializationObject.radiusRange = this.radiusRange;
serializationObject.directionRandomizer = this.directionRandomizer;
return serializationObject;
};
SphereParticleEmitter2.prototype.parse = function(serializationObject) {
this.radius = serializationObject.radius;
this.radiusRange = serializationObject.radiusRange;
this.directionRandomizer = serializationObject.directionRandomizer;
};
return SphereParticleEmitter2;
}()
);
BABYLON2.SphereParticleEmitter = SphereParticleEmitter;
var SphereDirectedParticleEmitter = (
/** @class */
function(_super) {
__extends(SphereDirectedParticleEmitter2, _super);
function SphereDirectedParticleEmitter2(radius, direction1, direction2) {
if (radius === void 0) {
radius = 1;
}
if (direction1 === void 0) {
direction1 = new BABYLON2.Vector3(0, 1, 0);
}
if (direction2 === void 0) {
direction2 = new BABYLON2.Vector3(0, 1, 0);
}
var _this = _super.call(this, radius) || this;
_this.direction1 = direction1;
_this.direction2 = direction2;
return _this;
}
SphereDirectedParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
var randX = BABYLON2.Scalar.RandomRange(this.direction1.x, this.direction2.x);
var randY = BABYLON2.Scalar.RandomRange(this.direction1.y, this.direction2.y);
var randZ = BABYLON2.Scalar.RandomRange(this.direction1.z, this.direction2.z);
BABYLON2.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
};
SphereDirectedParticleEmitter2.prototype.clone = function() {
var newOne = new SphereDirectedParticleEmitter2(this.radius, this.direction1, this.direction2);
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
SphereDirectedParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setFloat("radius", this.radius);
effect.setFloat("radiusRange", this.radiusRange);
effect.setVector3("direction1", this.direction1);
effect.setVector3("direction2", this.direction2);
};
SphereDirectedParticleEmitter2.prototype.getEffectDefines = function() {
return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
};
SphereDirectedParticleEmitter2.prototype.getClassName = function() {
return "SphereDirectedParticleEmitter";
};
SphereDirectedParticleEmitter2.prototype.serialize = function() {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.direction1 = this.direction1.asArray();
serializationObject.direction2 = this.direction2.asArray();
return serializationObject;
};
SphereDirectedParticleEmitter2.prototype.parse = function(serializationObject) {
_super.prototype.parse.call(this, serializationObject);
this.direction1.copyFrom(serializationObject.direction1);
this.direction2.copyFrom(serializationObject.direction2);
};
return SphereDirectedParticleEmitter2;
}(SphereParticleEmitter)
);
BABYLON2.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var HemisphericParticleEmitter = (
/** @class */
function() {
function HemisphericParticleEmitter2(radius, radiusRange, directionRandomizer) {
if (radius === void 0) {
radius = 1;
}
if (radiusRange === void 0) {
radiusRange = 1;
}
if (directionRandomizer === void 0) {
directionRandomizer = 0;
}
this.radius = radius;
this.radiusRange = radiusRange;
this.directionRandomizer = directionRandomizer;
}
HemisphericParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
var randX = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
var randY = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
var randZ = BABYLON2.Scalar.RandomRange(0, this.directionRandomizer);
direction.x += randX;
direction.y += randY;
direction.z += randZ;
direction.normalize();
BABYLON2.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
};
HemisphericParticleEmitter2.prototype.startPositionFunction = function(worldMatrix, positionToUpdate, particle) {
var randRadius = this.radius - BABYLON2.Scalar.RandomRange(0, this.radius * this.radiusRange);
var v = BABYLON2.Scalar.RandomRange(0, 1);
var phi = BABYLON2.Scalar.RandomRange(0, 2 * Math.PI);
var theta = Math.acos(2 * v - 1);
var randX = randRadius * Math.cos(phi) * Math.sin(theta);
var randY = randRadius * Math.cos(theta);
var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
};
HemisphericParticleEmitter2.prototype.clone = function() {
var newOne = new HemisphericParticleEmitter2(this.radius, this.directionRandomizer);
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
HemisphericParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setFloat("radius", this.radius);
effect.setFloat("radiusRange", this.radiusRange);
effect.setFloat("directionRandomizer", this.directionRandomizer);
};
HemisphericParticleEmitter2.prototype.getEffectDefines = function() {
return "#define HEMISPHERICEMITTER";
};
HemisphericParticleEmitter2.prototype.getClassName = function() {
return "HemisphericParticleEmitter";
};
HemisphericParticleEmitter2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.type = this.getClassName();
serializationObject.radius = this.radius;
serializationObject.radiusRange = this.radiusRange;
serializationObject.directionRandomizer = this.directionRandomizer;
return serializationObject;
};
HemisphericParticleEmitter2.prototype.parse = function(serializationObject) {
this.radius = serializationObject.radius;
this.radiusRange = serializationObject.radiusRange;
this.directionRandomizer = serializationObject.directionRandomizer;
};
return HemisphericParticleEmitter2;
}()
);
BABYLON2.HemisphericParticleEmitter = HemisphericParticleEmitter;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PointParticleEmitter = (
/** @class */
function() {
function PointParticleEmitter2() {
this.direction1 = new BABYLON2.Vector3(0, 1, 0);
this.direction2 = new BABYLON2.Vector3(0, 1, 0);
}
PointParticleEmitter2.prototype.startDirectionFunction = function(worldMatrix, directionToUpdate, particle) {
var randX = BABYLON2.Scalar.RandomRange(this.direction1.x, this.direction2.x);
var randY = BABYLON2.Scalar.RandomRange(this.direction1.y, this.direction2.y);
var randZ = BABYLON2.Scalar.RandomRange(this.direction1.z, this.direction2.z);
BABYLON2.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
};
PointParticleEmitter2.prototype.startPositionFunction = function(worldMatrix, positionToUpdate, particle) {
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
};
PointParticleEmitter2.prototype.clone = function() {
var newOne = new PointParticleEmitter2();
BABYLON2.Tools.DeepCopy(this, newOne);
return newOne;
};
PointParticleEmitter2.prototype.applyToShader = function(effect) {
effect.setVector3("direction1", this.direction1);
effect.setVector3("direction2", this.direction2);
};
PointParticleEmitter2.prototype.getEffectDefines = function() {
return "#define POINTEMITTER";
};
PointParticleEmitter2.prototype.getClassName = function() {
return "PointParticleEmitter";
};
PointParticleEmitter2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.type = this.getClassName();
serializationObject.direction1 = this.direction1.asArray();
serializationObject.direction2 = this.direction2.asArray();
return serializationObject;
};
PointParticleEmitter2.prototype.parse = function(serializationObject) {
BABYLON2.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
BABYLON2.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
};
return PointParticleEmitter2;
}()
);
BABYLON2.PointParticleEmitter = PointParticleEmitter;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractScene.AddParser(BABYLON2.SceneComponentConstants.NAME_PARTICLESYSTEM, function(parsedData, scene, container, rootUrl) {
var individualParser = BABYLON2.AbstractScene.GetIndividualParser(BABYLON2.SceneComponentConstants.NAME_PARTICLESYSTEM);
if (!individualParser) {
return;
}
if (parsedData.particleSystems !== void 0 && parsedData.particleSystems !== null) {
for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
var parsedParticleSystem = parsedData.particleSystems[index];
container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
}
}
});
BABYLON2.AbstractScene.AddIndividualParser(BABYLON2.SceneComponentConstants.NAME_PARTICLESYSTEM, function(parsedParticleSystem, scene, rootUrl) {
if (parsedParticleSystem.activeParticleCount) {
var ps = BABYLON2.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
return ps;
} else {
var ps = BABYLON2.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
return ps;
}
});
BABYLON2.Engine.prototype.createEffectForParticles = function(fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
if (uniformsNames === void 0) {
uniformsNames = [];
}
if (samplers === void 0) {
samplers = [];
}
if (defines === void 0) {
defines = "";
}
var attributesNamesOrOptions = BABYLON2.ParticleSystem._GetAttributeNamesOrOptions();
var effectCreationOption = BABYLON2.ParticleSystem._GetEffectCreationOptions();
if (defines.indexOf(" BILLBOARD") === -1) {
defines += "\n#define BILLBOARD\n";
}
if (samplers.indexOf("diffuseSampler") === -1) {
samplers.push("diffuseSampler");
}
return this.createEffect({
vertex: "particles",
fragmentElement: fragmentName
}, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
};
BABYLON2.Mesh.prototype.getEmittedParticleSystems = function() {
var results = new Array();
for (var index = 0; index < this.getScene().particleSystems.length; index++) {
var particleSystem = this.getScene().particleSystems[index];
if (particleSystem.emitter === this) {
results.push(particleSystem);
}
}
return results;
};
BABYLON2.Mesh.prototype.getHierarchyEmittedParticleSystems = function() {
var results = new Array();
var descendants = this.getDescendants();
descendants.push(this);
for (var index = 0; index < this.getScene().particleSystems.length; index++) {
var particleSystem = this.getScene().particleSystems[index];
var emitter = particleSystem.emitter;
if (emitter.position && descendants.indexOf(emitter) !== -1) {
results.push(particleSystem);
}
}
return results;
};
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SubEmitterType;
(function(SubEmitterType2) {
SubEmitterType2[SubEmitterType2["ATTACHED"] = 0] = "ATTACHED";
SubEmitterType2[SubEmitterType2["END"] = 1] = "END";
})(SubEmitterType = BABYLON2.SubEmitterType || (BABYLON2.SubEmitterType = {}));
var SubEmitter = (
/** @class */
function() {
function SubEmitter2(particleSystem) {
this.particleSystem = particleSystem;
this.type = SubEmitterType.END;
this.inheritDirection = false;
this.inheritedVelocityAmount = 0;
if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
particleSystem.emitter = new BABYLON2.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
}
particleSystem.onDisposeObservable.add(function() {
if (particleSystem.emitter && particleSystem.emitter.dispose) {
particleSystem.emitter.dispose();
}
});
}
SubEmitter2.prototype.clone = function() {
var emitter = this.particleSystem.emitter;
if (!emitter) {
emitter = new BABYLON2.Vector3();
} else if (emitter instanceof BABYLON2.Vector3) {
emitter = emitter.clone();
} else if (emitter instanceof BABYLON2.AbstractMesh) {
emitter = new BABYLON2.Mesh("", emitter.getScene());
emitter.isVisible = false;
}
var clone = new SubEmitter2(this.particleSystem.clone("", emitter));
clone.type = this.type;
clone.inheritDirection = this.inheritDirection;
clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
clone.particleSystem._disposeEmitterOnDispose = true;
clone.particleSystem.disposeOnStop = true;
return clone;
};
SubEmitter2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.type = this.type;
serializationObject.inheritDirection = this.inheritDirection;
serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
serializationObject.particleSystem = this.particleSystem.serialize();
return serializationObject;
};
SubEmitter2.Parse = function(serializationObject, scene, rootUrl) {
var system = serializationObject.particleSystem;
var subEmitter = new SubEmitter2(BABYLON2.ParticleSystem.Parse(system, scene, rootUrl));
subEmitter.type = serializationObject.type;
subEmitter.inheritDirection = serializationObject.inheritDirection;
subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
subEmitter.particleSystem._isSubEmitter = true;
return subEmitter;
};
SubEmitter2.prototype.dispose = function() {
this.particleSystem.dispose();
};
return SubEmitter2;
}()
);
BABYLON2.SubEmitter = SubEmitter;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ShaderMaterial = (
/** @class */
function(_super) {
__extends(ShaderMaterial2, _super);
function ShaderMaterial2(name, scene, shaderPath, options) {
if (options === void 0) {
options = {};
}
var _this = _super.call(this, name, scene) || this;
_this._textures = {};
_this._textureArrays = {};
_this._floats = {};
_this._ints = {};
_this._floatsArrays = {};
_this._colors3 = {};
_this._colors3Arrays = {};
_this._colors4 = {};
_this._vectors2 = {};
_this._vectors3 = {};
_this._vectors4 = {};
_this._matrices = {};
_this._matrices3x3 = {};
_this._matrices2x2 = {};
_this._vectors2Arrays = {};
_this._vectors3Arrays = {};
_this._cachedWorldViewMatrix = new BABYLON2.Matrix();
_this._shaderPath = shaderPath;
_this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
return _this;
}
ShaderMaterial2.prototype.getClassName = function() {
return "ShaderMaterial";
};
ShaderMaterial2.prototype.needAlphaBlending = function() {
return this.alpha < 1 || this._options.needAlphaBlending;
};
ShaderMaterial2.prototype.needAlphaTesting = function() {
return this._options.needAlphaTesting;
};
ShaderMaterial2.prototype._checkUniform = function(uniformName) {
if (this._options.uniforms.indexOf(uniformName) === -1) {
this._options.uniforms.push(uniformName);
}
};
ShaderMaterial2.prototype.setTexture = function(name, texture) {
if (this._options.samplers.indexOf(name) === -1) {
this._options.samplers.push(name);
}
this._textures[name] = texture;
return this;
};
ShaderMaterial2.prototype.setTextureArray = function(name, textures) {
if (this._options.samplers.indexOf(name) === -1) {
this._options.samplers.push(name);
}
this._checkUniform(name);
this._textureArrays[name] = textures;
return this;
};
ShaderMaterial2.prototype.setFloat = function(name, value) {
this._checkUniform(name);
this._floats[name] = value;
return this;
};
ShaderMaterial2.prototype.setInt = function(name, value) {
this._checkUniform(name);
this._ints[name] = value;
return this;
};
ShaderMaterial2.prototype.setFloats = function(name, value) {
this._checkUniform(name);
this._floatsArrays[name] = value;
return this;
};
ShaderMaterial2.prototype.setColor3 = function(name, value) {
this._checkUniform(name);
this._colors3[name] = value;
return this;
};
ShaderMaterial2.prototype.setColor3Array = function(name, value) {
this._checkUniform(name);
this._colors3Arrays[name] = value.reduce(function(arr, color) {
color.toArray(arr, arr.length);
return arr;
}, []);
return this;
};
ShaderMaterial2.prototype.setColor4 = function(name, value) {
this._checkUniform(name);
this._colors4[name] = value;
return this;
};
ShaderMaterial2.prototype.setVector2 = function(name, value) {
this._checkUniform(name);
this._vectors2[name] = value;
return this;
};
ShaderMaterial2.prototype.setVector3 = function(name, value) {
this._checkUniform(name);
this._vectors3[name] = value;
return this;
};
ShaderMaterial2.prototype.setVector4 = function(name, value) {
this._checkUniform(name);
this._vectors4[name] = value;
return this;
};
ShaderMaterial2.prototype.setMatrix = function(name, value) {
this._checkUniform(name);
this._matrices[name] = value;
return this;
};
ShaderMaterial2.prototype.setMatrix3x3 = function(name, value) {
this._checkUniform(name);
this._matrices3x3[name] = value;
return this;
};
ShaderMaterial2.prototype.setMatrix2x2 = function(name, value) {
this._checkUniform(name);
this._matrices2x2[name] = value;
return this;
};
ShaderMaterial2.prototype.setArray2 = function(name, value) {
this._checkUniform(name);
this._vectors2Arrays[name] = value;
return this;
};
ShaderMaterial2.prototype.setArray3 = function(name, value) {
this._checkUniform(name);
this._vectors3Arrays[name] = value;
return this;
};
ShaderMaterial2.prototype._checkCache = function(scene, mesh2, useInstances) {
if (!mesh2) {
return true;
}
if (this._effect && this._effect.defines.indexOf("#define INSTANCES") !== -1 !== useInstances) {
return false;
}
return false;
};
ShaderMaterial2.prototype.isReady = function(mesh2, useInstances) {
var scene = this.getScene();
var engine = scene.getEngine();
if (!this.checkReadyOnEveryCall) {
if (this._renderId === scene.getRenderId()) {
if (this._checkCache(scene, mesh2, useInstances)) {
return true;
}
}
}
var defines = [];
var attribs = [];
var fallbacks = new BABYLON2.EffectFallbacks();
for (var index = 0; index < this._options.defines.length; index++) {
defines.push(this._options.defines[index]);
}
for (var index = 0; index < this._options.attributes.length; index++) {
attribs.push(this._options.attributes[index]);
}
if (mesh2 && mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.ColorKind)) {
attribs.push(BABYLON2.VertexBuffer.ColorKind);
defines.push("#define VERTEXCOLOR");
}
if (useInstances) {
defines.push("#define INSTANCES");
BABYLON2.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
}
if (mesh2 && mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (mesh2.numBoneInfluencers > 4) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
defines.push("#define BonesPerMesh " + (mesh2.skeleton.bones.length + 1));
fallbacks.addCPUSkinningFallback(0, mesh2);
if (this._options.uniforms.indexOf("mBones") === -1) {
this._options.uniforms.push("mBones");
}
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
for (var name in this._textures) {
if (!this._textures[name].isReady()) {
return false;
}
}
if (mesh2 && this._shouldTurnAlphaTestOn(mesh2)) {
defines.push("#define ALPHATEST");
}
var previousEffect = this._effect;
var join = defines.join("\n");
this._effect = engine.createEffect(this._shaderPath, {
attributes: attribs,
uniformsNames: this._options.uniforms,
uniformBuffersNames: this._options.uniformBuffers,
samplers: this._options.samplers,
defines: join,
fallbacks,
onCompiled: this.onCompiled,
onError: this.onError
}, engine);
if (!this._effect.isReady()) {
return false;
}
if (previousEffect !== this._effect) {
scene.resetCachedMaterial();
}
this._renderId = scene.getRenderId();
return true;
};
ShaderMaterial2.prototype.bindOnlyWorldMatrix = function(world) {
var scene = this.getScene();
if (!this._effect) {
return;
}
if (this._options.uniforms.indexOf("world") !== -1) {
this._effect.setMatrix("world", world);
}
if (this._options.uniforms.indexOf("worldView") !== -1) {
world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
}
if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
}
};
ShaderMaterial2.prototype.bind = function(world, mesh2) {
this.bindOnlyWorldMatrix(world);
if (this._effect && this.getScene().getCachedMaterial() !== this) {
if (this._options.uniforms.indexOf("view") !== -1) {
this._effect.setMatrix("view", this.getScene().getViewMatrix());
}
if (this._options.uniforms.indexOf("projection") !== -1) {
this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
}
if (this._options.uniforms.indexOf("viewProjection") !== -1) {
this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
}
BABYLON2.MaterialHelper.BindBonesParameters(mesh2, this._effect);
var name;
for (name in this._textures) {
this._effect.setTexture(name, this._textures[name]);
}
for (name in this._textureArrays) {
this._effect.setTextureArray(name, this._textureArrays[name]);
}
for (name in this._ints) {
this._effect.setInt(name, this._ints[name]);
}
for (name in this._floats) {
this._effect.setFloat(name, this._floats[name]);
}
for (name in this._floatsArrays) {
this._effect.setArray(name, this._floatsArrays[name]);
}
for (name in this._colors3) {
this._effect.setColor3(name, this._colors3[name]);
}
for (name in this._colors3Arrays) {
this._effect.setArray3(name, this._colors3Arrays[name]);
}
for (name in this._colors4) {
var color = this._colors4[name];
this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
}
for (name in this._vectors2) {
this._effect.setVector2(name, this._vectors2[name]);
}
for (name in this._vectors3) {
this._effect.setVector3(name, this._vectors3[name]);
}
for (name in this._vectors4) {
this._effect.setVector4(name, this._vectors4[name]);
}
for (name in this._matrices) {
this._effect.setMatrix(name, this._matrices[name]);
}
for (name in this._matrices3x3) {
this._effect.setMatrix3x3(name, this._matrices3x3[name]);
}
for (name in this._matrices2x2) {
this._effect.setMatrix2x2(name, this._matrices2x2[name]);
}
for (name in this._vectors2Arrays) {
this._effect.setArray2(name, this._vectors2Arrays[name]);
}
for (name in this._vectors3Arrays) {
this._effect.setArray3(name, this._vectors3Arrays[name]);
}
}
this._afterBind(mesh2);
};
ShaderMaterial2.prototype.getActiveTextures = function() {
var activeTextures = _super.prototype.getActiveTextures.call(this);
for (var name in this._textures) {
activeTextures.push(this._textures[name]);
}
for (var name in this._textureArrays) {
var array = this._textureArrays[name];
for (var index = 0; index < array.length; index++) {
activeTextures.push(array[index]);
}
}
return activeTextures;
};
ShaderMaterial2.prototype.hasTexture = function(texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
for (var name in this._textures) {
if (this._textures[name] === texture) {
return true;
}
}
for (var name in this._textureArrays) {
var array = this._textureArrays[name];
for (var index = 0; index < array.length; index++) {
if (array[index] === texture) {
return true;
}
}
}
return false;
};
ShaderMaterial2.prototype.clone = function(name, scene) {
var newShaderMaterial = new ShaderMaterial2(name, scene || this.getScene(), this._shaderPath, this._options);
return newShaderMaterial;
};
ShaderMaterial2.prototype.dispose = function(forceDisposeEffect, forceDisposeTextures) {
if (forceDisposeTextures) {
var name;
for (name in this._textures) {
this._textures[name].dispose();
}
for (name in this._textureArrays) {
var array = this._textureArrays[name];
for (var index = 0; index < array.length; index++) {
array[index].dispose();
}
}
}
this._textures = {};
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
};
ShaderMaterial2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.ShaderMaterial";
serializationObject.options = this._options;
serializationObject.shaderPath = this._shaderPath;
var name;
serializationObject.textures = {};
for (name in this._textures) {
serializationObject.textures[name] = this._textures[name].serialize();
}
serializationObject.textureArrays = {};
for (name in this._textureArrays) {
serializationObject.textureArrays[name] = [];
var array = this._textureArrays[name];
for (var index = 0; index < array.length; index++) {
serializationObject.textureArrays[name].push(array[index].serialize());
}
}
serializationObject.floats = {};
for (name in this._floats) {
serializationObject.floats[name] = this._floats[name];
}
serializationObject.FloatArrays = {};
for (name in this._floatsArrays) {
serializationObject.FloatArrays[name] = this._floatsArrays[name];
}
serializationObject.colors3 = {};
for (name in this._colors3) {
serializationObject.colors3[name] = this._colors3[name].asArray();
}
serializationObject.colors3Arrays = {};
for (name in this._colors3Arrays) {
serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
}
serializationObject.colors4 = {};
for (name in this._colors4) {
serializationObject.colors4[name] = this._colors4[name].asArray();
}
serializationObject.vectors2 = {};
for (name in this._vectors2) {
serializationObject.vectors2[name] = this._vectors2[name].asArray();
}
serializationObject.vectors3 = {};
for (name in this._vectors3) {
serializationObject.vectors3[name] = this._vectors3[name].asArray();
}
serializationObject.vectors4 = {};
for (name in this._vectors4) {
serializationObject.vectors4[name] = this._vectors4[name].asArray();
}
serializationObject.matrices = {};
for (name in this._matrices) {
serializationObject.matrices[name] = this._matrices[name].asArray();
}
serializationObject.matrices3x3 = {};
for (name in this._matrices3x3) {
serializationObject.matrices3x3[name] = this._matrices3x3[name];
}
serializationObject.matrices2x2 = {};
for (name in this._matrices2x2) {
serializationObject.matrices2x2[name] = this._matrices2x2[name];
}
serializationObject.vectors2Arrays = {};
for (name in this._vectors2Arrays) {
serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
}
serializationObject.vectors3Arrays = {};
for (name in this._vectors3Arrays) {
serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
}
return serializationObject;
};
ShaderMaterial2.Parse = function(source, scene, rootUrl) {
var material = BABYLON2.SerializationHelper.Parse(function() {
return new ShaderMaterial2(source.name, scene, source.shaderPath, source.options);
}, source, scene, rootUrl);
var name;
for (name in source.textures) {
material.setTexture(name, BABYLON2.Texture.Parse(source.textures[name], scene, rootUrl));
}
for (name in source.textureArrays) {
var array = source.textureArrays[name];
var textureArray = new Array();
for (var index = 0; index < array.length; index++) {
textureArray.push(BABYLON2.Texture.Parse(array[index], scene, rootUrl));
}
material.setTextureArray(name, textureArray);
}
for (name in source.floats) {
material.setFloat(name, source.floats[name]);
}
for (name in source.floatsArrays) {
material.setFloats(name, source.floatsArrays[name]);
}
for (name in source.colors3) {
material.setColor3(name, BABYLON2.Color3.FromArray(source.colors3[name]));
}
for (name in source.colors3Arrays) {
var colors = source.colors3Arrays[name].reduce(function(arr, num, i2) {
if (i2 % 3 === 0) {
arr.push([num]);
} else {
arr[arr.length - 1].push(num);
}
return arr;
}, []).map(function(color) {
return BABYLON2.Color3.FromArray(color);
});
material.setColor3Array(name, colors);
}
for (name in source.colors4) {
material.setColor4(name, BABYLON2.Color4.FromArray(source.colors4[name]));
}
for (name in source.vectors2) {
material.setVector2(name, BABYLON2.Vector2.FromArray(source.vectors2[name]));
}
for (name in source.vectors3) {
material.setVector3(name, BABYLON2.Vector3.FromArray(source.vectors3[name]));
}
for (name in source.vectors4) {
material.setVector4(name, BABYLON2.Vector4.FromArray(source.vectors4[name]));
}
for (name in source.matrices) {
material.setMatrix(name, BABYLON2.Matrix.FromArray(source.matrices[name]));
}
for (name in source.matrices3x3) {
material.setMatrix3x3(name, source.matrices3x3[name]);
}
for (name in source.matrices2x2) {
material.setMatrix2x2(name, source.matrices2x2[name]);
}
for (name in source.vectors2Arrays) {
material.setArray2(name, source.vectors2Arrays[name]);
}
for (name in source.vectors3Arrays) {
material.setArray3(name, source.vectors3Arrays[name]);
}
return material;
};
return ShaderMaterial2;
}(BABYLON2.Material)
);
BABYLON2.ShaderMaterial = ShaderMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var GroundMesh = (
/** @class */
function(_super) {
__extends(GroundMesh2, _super);
function GroundMesh2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.generateOctree = false;
return _this;
}
GroundMesh2.prototype.getClassName = function() {
return "GroundMesh";
};
Object.defineProperty(GroundMesh2.prototype, "subdivisions", {
/**
* The minimum of x and y subdivisions
*/
get: function() {
return Math.min(this._subdivisionsX, this._subdivisionsY);
},
enumerable: true,
configurable: true
});
Object.defineProperty(GroundMesh2.prototype, "subdivisionsX", {
/**
* X subdivisions
*/
get: function() {
return this._subdivisionsX;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GroundMesh2.prototype, "subdivisionsY", {
/**
* Y subdivisions
*/
get: function() {
return this._subdivisionsY;
},
enumerable: true,
configurable: true
});
GroundMesh2.prototype.optimize = function(chunksCount, octreeBlocksSize) {
if (octreeBlocksSize === void 0) {
octreeBlocksSize = 32;
}
this._subdivisionsX = chunksCount;
this._subdivisionsY = chunksCount;
this.subdivide(chunksCount);
var thisAsAny = this;
if (thisAsAny.createOrUpdateSubmeshesOctree) {
thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
}
};
GroundMesh2.prototype.getHeightAtCoordinates = function(x, z) {
var world = this.getWorldMatrix();
var invMat = BABYLON2.Tmp.Matrix[5];
world.invertToRef(invMat);
var tmpVect = BABYLON2.Tmp.Vector3[8];
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(x, 0, z, invMat, tmpVect);
x = tmpVect.x;
z = tmpVect.z;
if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
return this.position.y;
}
if (!this._heightQuads || this._heightQuads.length == 0) {
this._initHeightQuads();
this._computeHeightQuads();
}
var facet = this._getFacetAt(x, z);
var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(0, y, 0, world, tmpVect);
return tmpVect.y;
};
GroundMesh2.prototype.getNormalAtCoordinates = function(x, z) {
var normal = new BABYLON2.Vector3(0, 1, 0);
this.getNormalAtCoordinatesToRef(x, z, normal);
return normal;
};
GroundMesh2.prototype.getNormalAtCoordinatesToRef = function(x, z, ref) {
var world = this.getWorldMatrix();
var tmpMat = BABYLON2.Tmp.Matrix[5];
world.invertToRef(tmpMat);
var tmpVect = BABYLON2.Tmp.Vector3[8];
BABYLON2.Vector3.TransformCoordinatesFromFloatsToRef(x, 0, z, tmpMat, tmpVect);
x = tmpVect.x;
z = tmpVect.z;
if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
return this;
}
if (!this._heightQuads || this._heightQuads.length == 0) {
this._initHeightQuads();
this._computeHeightQuads();
}
var facet = this._getFacetAt(x, z);
BABYLON2.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
return this;
};
GroundMesh2.prototype.updateCoordinateHeights = function() {
if (!this._heightQuads || this._heightQuads.length == 0) {
this._initHeightQuads();
}
this._computeHeightQuads();
return this;
};
GroundMesh2.prototype._getFacetAt = function(x, z) {
var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
var quad = this._heightQuads[row * this._subdivisionsX + col];
var facet;
if (z < quad.slope.x * x + quad.slope.y) {
facet = quad.facet1;
} else {
facet = quad.facet2;
}
return facet;
};
GroundMesh2.prototype._initHeightQuads = function() {
var subdivisionsX = this._subdivisionsX;
var subdivisionsY = this._subdivisionsY;
this._heightQuads = new Array();
for (var row = 0; row < subdivisionsY; row++) {
for (var col = 0; col < subdivisionsX; col++) {
var quad = { slope: BABYLON2.Vector2.Zero(), facet1: new BABYLON2.Vector4(0, 0, 0, 0), facet2: new BABYLON2.Vector4(0, 0, 0, 0) };
this._heightQuads[row * subdivisionsX + col] = quad;
}
}
return this;
};
GroundMesh2.prototype._computeHeightQuads = function() {
var positions = this.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
if (!positions) {
return this;
}
var v1 = BABYLON2.Tmp.Vector3[3];
var v2 = BABYLON2.Tmp.Vector3[2];
var v3 = BABYLON2.Tmp.Vector3[1];
var v4 = BABYLON2.Tmp.Vector3[0];
var v1v2 = BABYLON2.Tmp.Vector3[4];
var v1v3 = BABYLON2.Tmp.Vector3[5];
var v1v4 = BABYLON2.Tmp.Vector3[6];
var norm1 = BABYLON2.Tmp.Vector3[7];
var norm2 = BABYLON2.Tmp.Vector3[8];
var i2 = 0;
var j = 0;
var k = 0;
var cd = 0;
var h = 0;
var d1 = 0;
var d2 = 0;
var subdivisionsX = this._subdivisionsX;
var subdivisionsY = this._subdivisionsY;
for (var row = 0; row < subdivisionsY; row++) {
for (var col = 0; col < subdivisionsX; col++) {
i2 = col * 3;
j = row * (subdivisionsX + 1) * 3;
k = (row + 1) * (subdivisionsX + 1) * 3;
v1.x = positions[j + i2];
v1.y = positions[j + i2 + 1];
v1.z = positions[j + i2 + 2];
v2.x = positions[j + i2 + 3];
v2.y = positions[j + i2 + 4];
v2.z = positions[j + i2 + 5];
v3.x = positions[k + i2];
v3.y = positions[k + i2 + 1];
v3.z = positions[k + i2 + 2];
v4.x = positions[k + i2 + 3];
v4.y = positions[k + i2 + 4];
v4.z = positions[k + i2 + 5];
cd = (v4.z - v1.z) / (v4.x - v1.x);
h = v1.z - cd * v1.x;
v2.subtractToRef(v1, v1v2);
v3.subtractToRef(v1, v1v3);
v4.subtractToRef(v1, v1v4);
BABYLON2.Vector3.CrossToRef(v1v4, v1v3, norm1);
BABYLON2.Vector3.CrossToRef(v1v2, v1v4, norm2);
norm1.normalize();
norm2.normalize();
d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
var quad = this._heightQuads[row * subdivisionsX + col];
quad.slope.copyFromFloats(cd, h);
quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
}
}
return this;
};
GroundMesh2.prototype.serialize = function(serializationObject) {
_super.prototype.serialize.call(this, serializationObject);
serializationObject.subdivisionsX = this._subdivisionsX;
serializationObject.subdivisionsY = this._subdivisionsY;
serializationObject.minX = this._minX;
serializationObject.maxX = this._maxX;
serializationObject.minZ = this._minZ;
serializationObject.maxZ = this._maxZ;
serializationObject.width = this._width;
serializationObject.height = this._height;
};
GroundMesh2.Parse = function(parsedMesh, scene) {
var result = new GroundMesh2(parsedMesh.name, scene);
result._subdivisionsX = parsedMesh.subdivisionsX || 1;
result._subdivisionsY = parsedMesh.subdivisionsY || 1;
result._minX = parsedMesh.minX;
result._maxX = parsedMesh.maxX;
result._minZ = parsedMesh.minZ;
result._maxZ = parsedMesh.maxZ;
result._width = parsedMesh.width;
result._height = parsedMesh.height;
return result;
};
return GroundMesh2;
}(BABYLON2.Mesh)
);
BABYLON2.GroundMesh = GroundMesh;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var InstancedMesh = (
/** @class */
function(_super) {
__extends(InstancedMesh2, _super);
function InstancedMesh2(name, source) {
var _this = _super.call(this, name, source.getScene()) || this;
source.instances.push(_this);
_this._sourceMesh = source;
_this.position.copyFrom(source.position);
_this.rotation.copyFrom(source.rotation);
_this.scaling.copyFrom(source.scaling);
if (source.rotationQuaternion) {
_this.rotationQuaternion = source.rotationQuaternion.clone();
}
_this.infiniteDistance = source.infiniteDistance;
_this.setPivotMatrix(source.getPivotMatrix());
_this.refreshBoundingInfo();
_this._syncSubMeshes();
return _this;
}
InstancedMesh2.prototype.getClassName = function() {
return "InstancedMesh";
};
Object.defineProperty(InstancedMesh2.prototype, "receiveShadows", {
// Methods
/**
* If the source mesh receives shadows
*/
get: function() {
return this._sourceMesh.receiveShadows;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InstancedMesh2.prototype, "material", {
/**
* The material of the source mesh
*/
get: function() {
return this._sourceMesh.material;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InstancedMesh2.prototype, "visibility", {
/**
* Visibility of the source mesh
*/
get: function() {
return this._sourceMesh.visibility;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InstancedMesh2.prototype, "skeleton", {
/**
* Skeleton of the source mesh
*/
get: function() {
return this._sourceMesh.skeleton;
},
enumerable: true,
configurable: true
});
Object.defineProperty(InstancedMesh2.prototype, "renderingGroupId", {
/**
* Rendering ground id of the source mesh
*/
get: function() {
return this._sourceMesh.renderingGroupId;
},
set: function(value) {
if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
return;
}
BABYLON2.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
},
enumerable: true,
configurable: true
});
InstancedMesh2.prototype.getTotalVertices = function() {
return this._sourceMesh.getTotalVertices();
};
Object.defineProperty(InstancedMesh2.prototype, "sourceMesh", {
/**
* The source mesh of the instance
*/
get: function() {
return this._sourceMesh;
},
enumerable: true,
configurable: true
});
InstancedMesh2.prototype.isReady = function(completeCheck) {
if (completeCheck === void 0) {
completeCheck = false;
}
return this._sourceMesh.isReady(completeCheck, true);
};
InstancedMesh2.prototype.getVerticesData = function(kind, copyWhenShared) {
return this._sourceMesh.getVerticesData(kind, copyWhenShared);
};
InstancedMesh2.prototype.setVerticesData = function(kind, data2, updatable, stride) {
if (this.sourceMesh) {
this.sourceMesh.setVerticesData(kind, data2, updatable, stride);
}
return this.sourceMesh;
};
InstancedMesh2.prototype.updateVerticesData = function(kind, data2, updateExtends, makeItUnique) {
if (this.sourceMesh) {
this.sourceMesh.updateVerticesData(kind, data2, updateExtends, makeItUnique);
}
return this.sourceMesh;
};
InstancedMesh2.prototype.setIndices = function(indices, totalVertices) {
if (totalVertices === void 0) {
totalVertices = null;
}
if (this.sourceMesh) {
this.sourceMesh.setIndices(indices, totalVertices);
}
return this.sourceMesh;
};
InstancedMesh2.prototype.isVerticesDataPresent = function(kind) {
return this._sourceMesh.isVerticesDataPresent(kind);
};
InstancedMesh2.prototype.getIndices = function() {
return this._sourceMesh.getIndices();
};
Object.defineProperty(InstancedMesh2.prototype, "_positions", {
get: function() {
return this._sourceMesh._positions;
},
enumerable: true,
configurable: true
});
InstancedMesh2.prototype.refreshBoundingInfo = function() {
var meshBB = this._sourceMesh.getBoundingInfo();
this._boundingInfo = new BABYLON2.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
this._updateBoundingInfo();
return this;
};
InstancedMesh2.prototype._preActivate = function() {
if (this._currentLOD) {
this._currentLOD._preActivate();
}
return this;
};
InstancedMesh2.prototype._activate = function(renderId) {
if (this._currentLOD) {
this._currentLOD._registerInstanceForRenderId(this, renderId);
}
return this;
};
InstancedMesh2.prototype.getLOD = function(camera2) {
if (!camera2) {
return this;
}
var boundingInfo = this.getBoundingInfo();
this._currentLOD = this.sourceMesh.getLOD(camera2, boundingInfo.boundingSphere);
if (this._currentLOD === this.sourceMesh) {
return this;
}
return this._currentLOD;
};
InstancedMesh2.prototype._syncSubMeshes = function() {
this.releaseSubMeshes();
if (this._sourceMesh.subMeshes) {
for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
}
}
return this;
};
InstancedMesh2.prototype._generatePointsArray = function() {
return this._sourceMesh._generatePointsArray();
};
InstancedMesh2.prototype.clone = function(name, newParent, doNotCloneChildren) {
var result = this._sourceMesh.createInstance(name);
BABYLON2.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
this.refreshBoundingInfo();
if (newParent) {
result.parent = newParent;
}
if (!doNotCloneChildren) {
for (var index = 0; index < this.getScene().meshes.length; index++) {
var mesh2 = this.getScene().meshes[index];
if (mesh2.parent === this) {
mesh2.clone(mesh2.name, result);
}
}
}
result.computeWorldMatrix(true);
return result;
};
InstancedMesh2.prototype.dispose = function(doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) {
disposeMaterialAndTextures = false;
}
var index = this._sourceMesh.instances.indexOf(this);
this._sourceMesh.instances.splice(index, 1);
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
return InstancedMesh2;
}(BABYLON2.AbstractMesh)
);
BABYLON2.InstancedMesh = InstancedMesh;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var LinesMesh = (
/** @class */
function(_super) {
__extends(LinesMesh2, _super);
function LinesMesh2(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
if (scene === void 0) {
scene = null;
}
if (parent === void 0) {
parent = null;
}
var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
_this.useVertexColor = useVertexColor;
_this.useVertexAlpha = useVertexAlpha;
_this.color = new BABYLON2.Color3(1, 1, 1);
_this.alpha = 1;
if (source) {
_this.color = source.color.clone();
_this.alpha = source.alpha;
_this.useVertexColor = source.useVertexColor;
_this.useVertexAlpha = source.useVertexAlpha;
}
_this._intersectionThreshold = 0.1;
var defines = [];
var options = {
attributes: [BABYLON2.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
uniforms: ["world", "viewProjection"],
needAlphaBlending: true,
defines
};
if (useVertexAlpha === false) {
options.needAlphaBlending = false;
}
if (!useVertexColor) {
options.uniforms.push("color");
} else {
options.defines.push("#define VERTEXCOLOR");
options.attributes.push(BABYLON2.VertexBuffer.ColorKind);
}
_this._colorShader = new BABYLON2.ShaderMaterial("colorShader", _this.getScene(), "color", options);
return _this;
}
Object.defineProperty(LinesMesh2.prototype, "intersectionThreshold", {
/**
* The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
* This margin is expressed in world space coordinates, so its value may vary.
* Default value is 0.1
* @returns the intersection Threshold value.
*/
get: function() {
return this._intersectionThreshold;
},
/**
* The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
* This margin is expressed in world space coordinates, so its value may vary.
*/
set: function(value) {
if (this._intersectionThreshold === value) {
return;
}
this._intersectionThreshold = value;
if (this.geometry) {
this.geometry.boundingBias = new BABYLON2.Vector2(0, value);
}
},
enumerable: true,
configurable: true
});
LinesMesh2.prototype.getClassName = function() {
return "LinesMesh";
};
Object.defineProperty(LinesMesh2.prototype, "material", {
/**
* @hidden
*/
get: function() {
return this._colorShader;
},
/**
* @hidden
*/
set: function(value) {
},
enumerable: true,
configurable: true
});
Object.defineProperty(LinesMesh2.prototype, "checkCollisions", {
/**
* @hidden
*/
get: function() {
return false;
},
enumerable: true,
configurable: true
});
LinesMesh2.prototype._bind = function(subMesh, effect, fillMode) {
if (!this._geometry) {
return this;
}
this._geometry._bind(this._colorShader.getEffect());
if (!this.useVertexColor) {
this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
}
return this;
};
LinesMesh2.prototype._draw = function(subMesh, fillMode, instancesCount) {
if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) {
return this;
}
var engine = this.getScene().getEngine();
engine.drawElementsType(BABYLON2.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
return this;
};
LinesMesh2.prototype.dispose = function(doNotRecurse) {
this._colorShader.dispose();
_super.prototype.dispose.call(this, doNotRecurse);
};
LinesMesh2.prototype.clone = function(name, newParent, doNotCloneChildren) {
return new LinesMesh2(name, this.getScene(), newParent, this, doNotCloneChildren);
};
return LinesMesh2;
}(BABYLON2.Mesh)
);
BABYLON2.LinesMesh = LinesMesh;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var StringDictionary = (
/** @class */
function() {
function StringDictionary2() {
this._count = 0;
this._data = {};
}
StringDictionary2.prototype.copyFrom = function(source) {
var _this = this;
this.clear();
source.forEach(function(t, v) {
return _this.add(t, v);
});
};
StringDictionary2.prototype.get = function(key) {
var val = this._data[key];
if (val !== void 0) {
return val;
}
return void 0;
};
StringDictionary2.prototype.getOrAddWithFactory = function(key, factory) {
var val = this.get(key);
if (val !== void 0) {
return val;
}
val = factory(key);
if (val) {
this.add(key, val);
}
return val;
};
StringDictionary2.prototype.getOrAdd = function(key, val) {
var curVal = this.get(key);
if (curVal !== void 0) {
return curVal;
}
this.add(key, val);
return val;
};
StringDictionary2.prototype.contains = function(key) {
return this._data[key] !== void 0;
};
StringDictionary2.prototype.add = function(key, value) {
if (this._data[key] !== void 0) {
return false;
}
this._data[key] = value;
++this._count;
return true;
};
StringDictionary2.prototype.set = function(key, value) {
if (this._data[key] === void 0) {
return false;
}
this._data[key] = value;
return true;
};
StringDictionary2.prototype.getAndRemove = function(key) {
var val = this.get(key);
if (val !== void 0) {
delete this._data[key];
--this._count;
return val;
}
return null;
};
StringDictionary2.prototype.remove = function(key) {
if (this.contains(key)) {
delete this._data[key];
--this._count;
return true;
}
return false;
};
StringDictionary2.prototype.clear = function() {
this._data = {};
this._count = 0;
};
Object.defineProperty(StringDictionary2.prototype, "count", {
/**
* Gets the current count
*/
get: function() {
return this._count;
},
enumerable: true,
configurable: true
});
StringDictionary2.prototype.forEach = function(callback) {
for (var cur in this._data) {
var val = this._data[cur];
callback(cur, val);
}
};
StringDictionary2.prototype.first = function(callback) {
for (var cur in this._data) {
var val = this._data[cur];
var res = callback(cur, val);
if (res) {
return res;
}
}
return null;
};
return StringDictionary2;
}()
);
BABYLON2.StringDictionary = StringDictionary;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
Object.defineProperty(BABYLON2.Scene.prototype, "forceShowBoundingBoxes", {
get: function() {
return this._forceShowBoundingBoxes || false;
},
set: function(value) {
this._forceShowBoundingBoxes = value;
if (value) {
this.getBoundingBoxRenderer();
}
},
enumerable: true,
configurable: true
});
BABYLON2.Scene.prototype.getBoundingBoxRenderer = function() {
if (!this._boundingBoxRenderer) {
this._boundingBoxRenderer = new BoundingBoxRenderer(this);
}
return this._boundingBoxRenderer;
};
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "showBoundingBox", {
get: function() {
return this._showBoundingBox || false;
},
set: function(value) {
this._showBoundingBox = value;
if (value) {
this.getScene().getBoundingBoxRenderer();
}
},
enumerable: true,
configurable: true
});
var BoundingBoxRenderer = (
/** @class */
function() {
function BoundingBoxRenderer2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
this.frontColor = new BABYLON2.Color3(1, 1, 1);
this.backColor = new BABYLON2.Color3(0.1, 0.1, 0.1);
this.showBackLines = true;
this.renderList = new BABYLON2.SmartArray(32);
this._vertexBuffers = {};
this.scene = scene;
scene._addComponent(this);
}
BoundingBoxRenderer2.prototype.register = function() {
this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON2.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
this.scene._activeMeshStage.registerStep(BABYLON2.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
this.scene._evaluateSubMeshStage.registerStep(BABYLON2.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
};
BoundingBoxRenderer2.prototype._evaluateSubMesh = function(mesh2, subMesh) {
if (mesh2.showSubMeshesBoundingBox) {
var boundingInfo = subMesh.getBoundingInfo();
if (boundingInfo !== null && boundingInfo !== void 0) {
boundingInfo.boundingBox._tag = mesh2.renderingGroupId;
this.renderList.push(boundingInfo.boundingBox);
}
}
};
BoundingBoxRenderer2.prototype._activeMesh = function(sourceMesh, mesh2) {
if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
var boundingInfo = sourceMesh.getBoundingInfo();
boundingInfo.boundingBox._tag = mesh2.renderingGroupId;
this.renderList.push(boundingInfo.boundingBox);
}
};
BoundingBoxRenderer2.prototype._prepareRessources = function() {
if (this._colorShader) {
return;
}
this._colorShader = new BABYLON2.ShaderMaterial("colorShader", this.scene, "color", {
attributes: [BABYLON2.VertexBuffer.PositionKind],
uniforms: ["world", "viewProjection", "color"]
});
var engine = this.scene.getEngine();
var boxdata = BABYLON2.VertexData.CreateBox({ size: 1 });
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = new BABYLON2.VertexBuffer(engine, boxdata.positions, BABYLON2.VertexBuffer.PositionKind, false);
this._createIndexBuffer();
};
BoundingBoxRenderer2.prototype._createIndexBuffer = function() {
var engine = this.scene.getEngine();
this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
};
BoundingBoxRenderer2.prototype.rebuild = function() {
var vb = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vb) {
vb._rebuild();
}
this._createIndexBuffer();
};
BoundingBoxRenderer2.prototype.reset = function() {
this.renderList.reset();
};
BoundingBoxRenderer2.prototype.render = function(renderingGroupId) {
if (this.renderList.length === 0) {
return;
}
this._prepareRessources();
if (!this._colorShader.isReady()) {
return;
}
var engine = this.scene.getEngine();
engine.setDepthWrite(false);
this._colorShader._preBind();
for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
var boundingBox = this.renderList.data[boundingBoxIndex];
if (boundingBox._tag !== renderingGroupId) {
continue;
}
var min = boundingBox.minimum;
var max = boundingBox.maximum;
var diff = max.subtract(min);
var median = min.add(diff.scale(0.5));
var worldMatrix = BABYLON2.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON2.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
if (this.showBackLines) {
engine.setDepthFunctionToGreaterOrEqual();
this.scene.resetCachedMaterial();
this._colorShader.setColor4("color", this.backColor.toColor4());
this._colorShader.bind(worldMatrix);
engine.drawElementsType(BABYLON2.Material.LineListDrawMode, 0, 24);
}
engine.setDepthFunctionToLess();
this.scene.resetCachedMaterial();
this._colorShader.setColor4("color", this.frontColor.toColor4());
this._colorShader.bind(worldMatrix);
engine.drawElementsType(BABYLON2.Material.LineListDrawMode, 0, 24);
}
this._colorShader.unbind();
engine.setDepthFunctionToLessOrEqual();
engine.setDepthWrite(true);
};
BoundingBoxRenderer2.prototype.renderOcclusionBoundingBox = function(mesh2) {
this._prepareRessources();
if (!this._colorShader.isReady() || !mesh2._boundingInfo) {
return;
}
var engine = this.scene.getEngine();
engine.setDepthWrite(false);
engine.setColorWrite(false);
this._colorShader._preBind();
var boundingBox = mesh2._boundingInfo.boundingBox;
var min = boundingBox.minimum;
var max = boundingBox.maximum;
var diff = max.subtract(min);
var median = min.add(diff.scale(0.5));
var worldMatrix = BABYLON2.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON2.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
engine.setDepthFunctionToLess();
this.scene.resetCachedMaterial();
this._colorShader.bind(worldMatrix);
engine.drawElementsType(BABYLON2.Material.LineListDrawMode, 0, 24);
this._colorShader.unbind();
engine.setDepthFunctionToLessOrEqual();
engine.setDepthWrite(true);
engine.setColorWrite(true);
};
BoundingBoxRenderer2.prototype.dispose = function() {
if (!this._colorShader) {
return;
}
this.renderList.dispose();
this._colorShader.dispose();
var buffer = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (buffer) {
buffer.dispose();
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = null;
}
this.scene.getEngine()._releaseBuffer(this._indexBuffer);
};
return BoundingBoxRenderer2;
}()
);
BABYLON2.BoundingBoxRenderer = BoundingBoxRenderer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Engine.prototype.createTransformFeedback = function() {
return this._gl.createTransformFeedback();
};
BABYLON2.Engine.prototype.deleteTransformFeedback = function(value) {
this._gl.deleteTransformFeedback(value);
};
BABYLON2.Engine.prototype.bindTransformFeedback = function(value) {
this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
};
BABYLON2.Engine.prototype.beginTransformFeedback = function(usePoints) {
if (usePoints === void 0) {
usePoints = true;
}
this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
};
BABYLON2.Engine.prototype.endTransformFeedback = function() {
this._gl.endTransformFeedback();
};
BABYLON2.Engine.prototype.setTranformFeedbackVaryings = function(program, value) {
this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
};
BABYLON2.Engine.prototype.bindTransformFeedbackBuffer = function(value) {
this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
};
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var GPUParticleSystem = (
/** @class */
function(_super) {
__extends(GPUParticleSystem2, _super);
function GPUParticleSystem2(name, options, scene, isAnimationSheetEnabled) {
if (isAnimationSheetEnabled === void 0) {
isAnimationSheetEnabled = false;
}
var _this = _super.call(this, name) || this;
_this.layerMask = 268435455;
_this._accumulatedCount = 0;
_this._targetIndex = 0;
_this._currentRenderId = -1;
_this._started = false;
_this._stopped = false;
_this._timeDelta = 0;
_this._attributesStrideSize = 21;
_this._actualFrame = 0;
_this._rawTextureWidth = 256;
_this.onDisposeObservable = new BABYLON2.Observable();
_this.forceDepthWrite = false;
_this._preWarmDone = false;
_this._scene = scene || BABYLON2.Engine.LastCreatedScene;
_this._attachImageProcessingConfiguration(null);
_this._engine = _this._scene.getEngine();
if (!options.randomTextureSize) {
delete options.randomTextureSize;
}
var fullOptions = __assign({ capacity: 5e4, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
var optionsAsNumber = options;
if (isFinite(optionsAsNumber)) {
fullOptions.capacity = optionsAsNumber;
}
_this._capacity = fullOptions.capacity;
_this._activeCount = fullOptions.capacity;
_this._currentActiveCount = 0;
_this._isAnimationSheetEnabled = isAnimationSheetEnabled;
_this._scene.particleSystems.push(_this);
_this._updateEffectOptions = {
attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
uniformsNames: [
"currentCount",
"timeDelta",
"emitterWM",
"lifeTime",
"color1",
"color2",
"sizeRange",
"scaleRange",
"gravity",
"emitPower",
"direction1",
"direction2",
"minEmitBox",
"maxEmitBox",
"radius",
"directionRandomizer",
"height",
"coneAngle",
"stopFactor",
"angleRange",
"radiusRange",
"cellInfos",
"noiseStrength",
"limitVelocityDamping"
],
uniformBuffersNames: [],
samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
defines: "",
fallbacks: null,
onCompiled: null,
onError: null,
indexParameters: null,
maxSimultaneousLights: 0,
transformFeedbackVaryings: []
};
_this.particleEmitterType = new BABYLON2.BoxParticleEmitter();
var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
var d = [];
for (var i2 = 0; i2 < maxTextureSize; ++i2) {
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
}
_this._randomTexture = new BABYLON2.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON2.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON2.Texture.NEAREST_SAMPLINGMODE, BABYLON2.Engine.TEXTURETYPE_FLOAT);
_this._randomTexture.wrapU = BABYLON2.Texture.WRAP_ADDRESSMODE;
_this._randomTexture.wrapV = BABYLON2.Texture.WRAP_ADDRESSMODE;
d = [];
for (var i2 = 0; i2 < maxTextureSize; ++i2) {
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
d.push(Math.random());
}
_this._randomTexture2 = new BABYLON2.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON2.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON2.Texture.NEAREST_SAMPLINGMODE, BABYLON2.Engine.TEXTURETYPE_FLOAT);
_this._randomTexture2.wrapU = BABYLON2.Texture.WRAP_ADDRESSMODE;
_this._randomTexture2.wrapV = BABYLON2.Texture.WRAP_ADDRESSMODE;
_this._randomTextureSize = maxTextureSize;
return _this;
}
Object.defineProperty(GPUParticleSystem2, "IsSupported", {
/**
* Gets a boolean indicating if the GPU particles can be rendered on current browser
*/
get: function() {
if (!BABYLON2.Engine.LastCreatedEngine) {
return false;
}
return BABYLON2.Engine.LastCreatedEngine.webGLVersion > 1;
},
enumerable: true,
configurable: true
});
GPUParticleSystem2.prototype.getCapacity = function() {
return this._capacity;
};
Object.defineProperty(GPUParticleSystem2.prototype, "activeParticleCount", {
/**
* Gets or set the number of active particles
*/
get: function() {
return this._activeCount;
},
set: function(value) {
this._activeCount = Math.min(value, this._capacity);
},
enumerable: true,
configurable: true
});
GPUParticleSystem2.prototype.isReady = function() {
if (!this._updateEffect) {
this._recreateUpdateEffect();
this._recreateRenderEffect();
return false;
}
if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
return false;
}
return true;
};
GPUParticleSystem2.prototype.isStarted = function() {
return this._started;
};
GPUParticleSystem2.prototype.start = function(delay) {
var _this = this;
if (delay === void 0) {
delay = this.startDelay;
}
if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
}
if (delay) {
setTimeout(function() {
_this.start(0);
}, delay);
return;
}
this._started = true;
this._stopped = false;
this._preWarmDone = false;
if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
}
};
GPUParticleSystem2.prototype.stop = function() {
this._stopped = true;
};
GPUParticleSystem2.prototype.reset = function() {
this._releaseBuffers();
this._releaseVAOs();
this._currentActiveCount = 0;
this._targetIndex = 0;
};
GPUParticleSystem2.prototype.getClassName = function() {
return "GPUParticleSystem";
};
GPUParticleSystem2.prototype._removeGradientAndTexture = function(gradient, gradients, texture) {
_super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
this._releaseBuffers();
return this;
};
GPUParticleSystem2.prototype.addColorGradient = function(gradient, color1, color2) {
if (!this._colorGradients) {
this._colorGradients = [];
}
var colorGradient = new BABYLON2.ColorGradient();
colorGradient.gradient = gradient;
colorGradient.color1 = color1;
this._colorGradients.push(colorGradient);
this._colorGradients.sort(function(a, b2) {
if (a.gradient < b2.gradient) {
return -1;
} else if (a.gradient > b2.gradient) {
return 1;
}
return 0;
});
if (this._colorGradientsTexture) {
this._colorGradientsTexture.dispose();
this._colorGradientsTexture = null;
}
this._releaseBuffers();
return this;
};
GPUParticleSystem2.prototype.removeColorGradient = function(gradient) {
this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
this._colorGradientsTexture = null;
return this;
};
GPUParticleSystem2.prototype._addFactorGradient = function(factorGradients, gradient, factor) {
var valueGradient = new BABYLON2.FactorGradient();
valueGradient.gradient = gradient;
valueGradient.factor1 = factor;
factorGradients.push(valueGradient);
factorGradients.sort(function(a, b2) {
if (a.gradient < b2.gradient) {
return -1;
} else if (a.gradient > b2.gradient) {
return 1;
}
return 0;
});
this._releaseBuffers();
};
GPUParticleSystem2.prototype.addSizeGradient = function(gradient, factor) {
if (!this._sizeGradients) {
this._sizeGradients = [];
}
this._addFactorGradient(this._sizeGradients, gradient, factor);
if (this._sizeGradientsTexture) {
this._sizeGradientsTexture.dispose();
this._sizeGradientsTexture = null;
}
this._releaseBuffers();
return this;
};
GPUParticleSystem2.prototype.removeSizeGradient = function(gradient) {
this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
this._sizeGradientsTexture = null;
return this;
};
GPUParticleSystem2.prototype.addAngularSpeedGradient = function(gradient, factor) {
if (!this._angularSpeedGradients) {
this._angularSpeedGradients = [];
}
this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
if (this._angularSpeedGradientsTexture) {
this._angularSpeedGradientsTexture.dispose();
this._angularSpeedGradientsTexture = null;
}
this._releaseBuffers();
return this;
};
GPUParticleSystem2.prototype.removeAngularSpeedGradient = function(gradient) {
this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
this._angularSpeedGradientsTexture = null;
return this;
};
GPUParticleSystem2.prototype.addVelocityGradient = function(gradient, factor) {
if (!this._velocityGradients) {
this._velocityGradients = [];
}
this._addFactorGradient(this._velocityGradients, gradient, factor);
if (this._velocityGradientsTexture) {
this._velocityGradientsTexture.dispose();
this._velocityGradientsTexture = null;
}
this._releaseBuffers();
return this;
};
GPUParticleSystem2.prototype.removeVelocityGradient = function(gradient) {
this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
this._velocityGradientsTexture = null;
return this;
};
GPUParticleSystem2.prototype.addLimitVelocityGradient = function(gradient, factor) {
if (!this._limitVelocityGradients) {
this._limitVelocityGradients = [];
}
this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
if (this._limitVelocityGradientsTexture) {
this._limitVelocityGradientsTexture.dispose();
this._limitVelocityGradientsTexture = null;
}
this._releaseBuffers();
return this;
};
GPUParticleSystem2.prototype.removeLimitVelocityGradient = function(gradient) {
this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
this._limitVelocityGradientsTexture = null;
return this;
};
GPUParticleSystem2.prototype.addDragGradient = function(gradient, factor) {
if (!this._dragGradients) {
this._dragGradients = [];
}
this._addFactorGradient(this._dragGradients, gradient, factor);
if (this._dragGradientsTexture) {
this._dragGradientsTexture.dispose();
this._dragGradientsTexture = null;
}
this._releaseBuffers();
return this;
};
GPUParticleSystem2.prototype.removeDragGradient = function(gradient) {
this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
this._dragGradientsTexture = null;
return this;
};
GPUParticleSystem2.prototype.addEmitRateGradient = function(gradient, factor, factor2) {
return this;
};
GPUParticleSystem2.prototype.removeEmitRateGradient = function(gradient) {
return this;
};
GPUParticleSystem2.prototype.addStartSizeGradient = function(gradient, factor, factor2) {
return this;
};
GPUParticleSystem2.prototype.removeStartSizeGradient = function(gradient) {
return this;
};
GPUParticleSystem2.prototype.addColorRemapGradient = function(gradient, min, max) {
return this;
};
GPUParticleSystem2.prototype.removeColorRemapGradient = function(gradient) {
return this;
};
GPUParticleSystem2.prototype.addAlphaRemapGradient = function(gradient, min, max) {
return this;
};
GPUParticleSystem2.prototype.removeAlphaRemapGradient = function(gradient) {
return this;
};
GPUParticleSystem2.prototype.addRampGradient = function(gradient, color) {
return this;
};
GPUParticleSystem2.prototype.removeRampGradient = function(gradient) {
return this;
};
GPUParticleSystem2.prototype.getRampGradients = function() {
return null;
};
Object.defineProperty(GPUParticleSystem2.prototype, "useRampGradients", {
/**
* Not supported by GPUParticleSystem
* Gets or sets a boolean indicating that ramp gradients must be used
* @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
*/
get: function() {
return false;
},
set: function(value) {
},
enumerable: true,
configurable: true
});
GPUParticleSystem2.prototype.addLifeTimeGradient = function(gradient, factor, factor2) {
return this;
};
GPUParticleSystem2.prototype.removeLifeTimeGradient = function(gradient) {
return this;
};
GPUParticleSystem2.prototype._reset = function() {
this._releaseBuffers();
};
GPUParticleSystem2.prototype._createUpdateVAO = function(source) {
var updateVertexBuffers = {};
updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
var offset = 12;
if (!this._colorGradientsTexture) {
updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
offset += 4;
}
updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
offset += 3;
if (!this._isBillboardBased) {
updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
offset += 3;
}
if (this._angularSpeedGradientsTexture) {
updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
offset += 1;
} else {
updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
offset += 2;
}
if (this._isAnimationSheetEnabled) {
updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
offset += 1;
if (this.spriteRandomStartCell) {
updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
offset += 1;
}
}
if (this.noiseTexture) {
updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
offset += 3;
updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
offset += 3;
}
var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
this._engine.bindArrayBuffer(null);
return vao;
};
GPUParticleSystem2.prototype._createRenderVAO = function(source, spriteSource) {
var renderVertexBuffers = {};
renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
var offset = 12;
if (!this._colorGradientsTexture) {
renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
offset += 4;
}
if (this.billboardMode === BABYLON2.ParticleSystem.BILLBOARDMODE_STRETCHED) {
renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
}
offset += 3;
if (!this._isBillboardBased) {
renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
offset += 3;
}
renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
if (this._angularSpeedGradientsTexture) {
offset++;
} else {
offset += 2;
}
if (this._isAnimationSheetEnabled) {
renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
offset += 1;
if (this.spriteRandomStartCell) {
renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
offset += 1;
}
}
if (this.noiseTexture) {
renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
offset += 3;
renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
offset += 3;
}
renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
this._engine.bindArrayBuffer(null);
return vao;
};
GPUParticleSystem2.prototype._initialize = function(force) {
if (force === void 0) {
force = false;
}
if (this._buffer0 && !force) {
return;
}
var engine = this._scene.getEngine();
var data2 = new Array();
if (!this.isBillboardBased) {
this._attributesStrideSize += 3;
}
if (this._colorGradientsTexture) {
this._attributesStrideSize -= 4;
}
if (this._angularSpeedGradientsTexture) {
this._attributesStrideSize -= 1;
}
if (this._isAnimationSheetEnabled) {
this._attributesStrideSize += 1;
if (this.spriteRandomStartCell) {
this._attributesStrideSize += 1;
}
}
if (this.noiseTexture) {
this._attributesStrideSize += 6;
}
for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
data2.push(0);
data2.push(0);
data2.push(0);
data2.push(0);
data2.push(0);
data2.push(Math.random());
data2.push(Math.random());
data2.push(Math.random());
data2.push(Math.random());
data2.push(0);
data2.push(0);
data2.push(0);
if (!this._colorGradientsTexture) {
data2.push(0);
data2.push(0);
data2.push(0);
data2.push(0);
}
data2.push(0);
data2.push(0);
data2.push(0);
if (!this.isBillboardBased) {
data2.push(0);
data2.push(0);
data2.push(0);
}
data2.push(0);
if (!this._angularSpeedGradientsTexture) {
data2.push(0);
}
if (this._isAnimationSheetEnabled) {
data2.push(0);
if (this.spriteRandomStartCell) {
data2.push(0);
}
}
if (this.noiseTexture) {
data2.push(Math.random());
data2.push(Math.random());
data2.push(Math.random());
data2.push(Math.random());
data2.push(Math.random());
data2.push(Math.random());
}
}
var spriteData = new Float32Array([
0.5,
0.5,
1,
1,
-0.5,
0.5,
0,
1,
-0.5,
-0.5,
0,
0,
0.5,
-0.5,
1,
0
]);
this._buffer0 = new BABYLON2.Buffer(engine, data2, false, this._attributesStrideSize);
this._buffer1 = new BABYLON2.Buffer(engine, data2, false, this._attributesStrideSize);
this._spriteBuffer = new BABYLON2.Buffer(engine, spriteData, false, 4);
this._updateVAO = [];
this._updateVAO.push(this._createUpdateVAO(this._buffer0));
this._updateVAO.push(this._createUpdateVAO(this._buffer1));
this._renderVAO = [];
this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
this._sourceBuffer = this._buffer0;
this._targetBuffer = this._buffer1;
};
GPUParticleSystem2.prototype._recreateUpdateEffect = function() {
var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
if (this._isBillboardBased) {
defines += "\n#define BILLBOARD";
}
if (this._colorGradientsTexture) {
defines += "\n#define COLORGRADIENTS";
}
if (this._sizeGradientsTexture) {
defines += "\n#define SIZEGRADIENTS";
}
if (this._angularSpeedGradientsTexture) {
defines += "\n#define ANGULARSPEEDGRADIENTS";
}
if (this._velocityGradientsTexture) {
defines += "\n#define VELOCITYGRADIENTS";
}
if (this._limitVelocityGradientsTexture) {
defines += "\n#define LIMITVELOCITYGRADIENTS";
}
if (this._dragGradientsTexture) {
defines += "\n#define DRAGGRADIENTS";
}
if (this.isAnimationSheetEnabled) {
defines += "\n#define ANIMATESHEET";
if (this.spriteRandomStartCell) {
defines += "\n#define ANIMATESHEETRANDOMSTART";
}
}
if (this.noiseTexture) {
defines += "\n#define NOISE";
}
if (this._updateEffect && this._updateEffectOptions.defines === defines) {
return;
}
this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
if (!this._colorGradientsTexture) {
this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
}
this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
if (!this._isBillboardBased) {
this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
}
this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
if (this.isAnimationSheetEnabled) {
this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
if (this.spriteRandomStartCell) {
this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
}
}
if (this.noiseTexture) {
this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
}
this._updateEffectOptions.defines = defines;
this._updateEffect = new BABYLON2.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
};
GPUParticleSystem2.prototype._recreateRenderEffect = function() {
var defines = "";
if (this._scene.clipPlane) {
defines = "\n#define CLIPPLANE";
}
if (this._scene.clipPlane2) {
defines = "\n#define CLIPPLANE2";
}
if (this._scene.clipPlane3) {
defines = "\n#define CLIPPLANE3";
}
if (this._scene.clipPlane4) {
defines = "\n#define CLIPPLANE4";
}
if (this.blendMode === BABYLON2.ParticleSystem.BLENDMODE_MULTIPLY) {
defines = "\n#define BLENDMULTIPLYMODE";
}
if (this._isBillboardBased) {
defines += "\n#define BILLBOARD";
switch (this.billboardMode) {
case BABYLON2.ParticleSystem.BILLBOARDMODE_Y:
defines += "\n#define BILLBOARDY";
break;
case BABYLON2.ParticleSystem.BILLBOARDMODE_STRETCHED:
defines += "\n#define BILLBOARDSTRETCHED";
break;
case BABYLON2.ParticleSystem.BILLBOARDMODE_ALL:
default:
break;
}
}
if (this._colorGradientsTexture) {
defines += "\n#define COLORGRADIENTS";
}
if (this.isAnimationSheetEnabled) {
defines += "\n#define ANIMATESHEET";
}
if (this._imageProcessingConfiguration) {
this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
defines += "\n" + this._imageProcessingConfigurationDefines.toString();
}
if (this._renderEffect && this._renderEffect.defines === defines) {
return;
}
var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
var samplers = ["textureSampler", "colorGradientSampler"];
if (BABYLON2.ImageProcessingConfiguration) {
BABYLON2.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
BABYLON2.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
}
this._renderEffect = new BABYLON2.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
};
GPUParticleSystem2.prototype.animate = function(preWarm) {
if (preWarm === void 0) {
preWarm = false;
}
this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
this._actualFrame += this._timeDelta;
if (!this._stopped) {
if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
this.stop();
}
}
};
GPUParticleSystem2.prototype._createFactorGradientTexture = function(factorGradients, textureName) {
var texture = this[textureName];
if (!factorGradients || !factorGradients.length || texture) {
return;
}
var data2 = new Float32Array(this._rawTextureWidth);
for (var x = 0; x < this._rawTextureWidth; x++) {
var ratio = x / this._rawTextureWidth;
BABYLON2.Tools.GetCurrentGradient(ratio, factorGradients, function(currentGradient, nextGradient, scale) {
data2[x] = BABYLON2.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
});
}
this[textureName] = BABYLON2.RawTexture.CreateRTexture(data2, this._rawTextureWidth, 1, this._scene, false, false, BABYLON2.Texture.NEAREST_SAMPLINGMODE);
};
GPUParticleSystem2.prototype._createSizeGradientTexture = function() {
this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
};
GPUParticleSystem2.prototype._createAngularSpeedGradientTexture = function() {
this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
};
GPUParticleSystem2.prototype._createVelocityGradientTexture = function() {
this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
};
GPUParticleSystem2.prototype._createLimitVelocityGradientTexture = function() {
this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
};
GPUParticleSystem2.prototype._createDragGradientTexture = function() {
this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
};
GPUParticleSystem2.prototype._createColorGradientTexture = function() {
if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
return;
}
var data2 = new Uint8Array(this._rawTextureWidth * 4);
var tmpColor = BABYLON2.Tmp.Color4[0];
for (var x = 0; x < this._rawTextureWidth; x++) {
var ratio = x / this._rawTextureWidth;
BABYLON2.Tools.GetCurrentGradient(ratio, this._colorGradients, function(currentGradient, nextGradient, scale) {
BABYLON2.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
data2[x * 4] = tmpColor.r * 255;
data2[x * 4 + 1] = tmpColor.g * 255;
data2[x * 4 + 2] = tmpColor.b * 255;
data2[x * 4 + 3] = tmpColor.a * 255;
});
}
this._colorGradientsTexture = BABYLON2.RawTexture.CreateRGBATexture(data2, this._rawTextureWidth, 1, this._scene, false, false, BABYLON2.Texture.NEAREST_SAMPLINGMODE);
};
GPUParticleSystem2.prototype.render = function(preWarm) {
if (preWarm === void 0) {
preWarm = false;
}
if (!this._started) {
return 0;
}
this._createColorGradientTexture();
this._createSizeGradientTexture();
this._createAngularSpeedGradientTexture();
this._createVelocityGradientTexture();
this._createLimitVelocityGradientTexture();
this._createDragGradientTexture();
this._recreateUpdateEffect();
this._recreateRenderEffect();
if (!this.isReady()) {
return 0;
}
if (!preWarm) {
if (!this._preWarmDone && this.preWarmCycles) {
for (var index = 0; index < this.preWarmCycles; index++) {
this.animate(true);
this.render(true);
}
this._preWarmDone = true;
}
if (this._currentRenderId === this._scene.getRenderId()) {
return 0;
}
this._currentRenderId = this._scene.getRenderId();
}
this._initialize();
this._accumulatedCount += this.emitRate * this._timeDelta;
if (this._accumulatedCount > 1) {
var intPart = this._accumulatedCount | 0;
this._accumulatedCount -= intPart;
this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
}
if (!this._currentActiveCount) {
return 0;
}
this._engine.enableEffect(this._updateEffect);
this._engine.setState(false);
this._updateEffect.setFloat("currentCount", this._currentActiveCount);
this._updateEffect.setFloat("timeDelta", this._timeDelta);
this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
this._updateEffect.setTexture("randomSampler", this._randomTexture);
this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
if (!this._colorGradientsTexture) {
this._updateEffect.setDirectColor4("color1", this.color1);
this._updateEffect.setDirectColor4("color2", this.color2);
}
this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
this._updateEffect.setVector3("gravity", this.gravity);
if (this._sizeGradientsTexture) {
this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
}
if (this._angularSpeedGradientsTexture) {
this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
}
if (this._velocityGradientsTexture) {
this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
}
if (this._limitVelocityGradientsTexture) {
this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
}
if (this._dragGradientsTexture) {
this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
}
if (this.particleEmitterType) {
this.particleEmitterType.applyToShader(this._updateEffect);
}
if (this._isAnimationSheetEnabled) {
this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
}
if (this.noiseTexture) {
this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
}
var emitterWM;
if (this.emitter.position) {
var emitterMesh = this.emitter;
emitterWM = emitterMesh.getWorldMatrix();
} else {
var emitterPosition = this.emitter;
emitterWM = BABYLON2.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
}
this._updateEffect.setMatrix("emitterWM", emitterWM);
this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
this._engine.setRasterizerState(false);
this._engine.beginTransformFeedback(true);
this._engine.drawArraysType(BABYLON2.Material.PointListDrawMode, 0, this._currentActiveCount);
this._engine.endTransformFeedback();
this._engine.setRasterizerState(true);
this._engine.bindTransformFeedbackBuffer(null);
if (!preWarm) {
this._engine.enableEffect(this._renderEffect);
var viewMatrix = this._scene.getViewMatrix();
this._renderEffect.setMatrix("view", viewMatrix);
this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
this._renderEffect.setTexture("textureSampler", this.particleTexture);
this._renderEffect.setVector2("translationPivot", this.translationPivot);
if (this._colorGradientsTexture) {
this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
} else {
this._renderEffect.setDirectColor4("colorDead", this.colorDead);
}
if (this._isAnimationSheetEnabled && this.particleTexture) {
var baseSize = this.particleTexture.getBaseSize();
this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
}
if (this._isBillboardBased) {
var camera2 = this._scene.activeCamera;
this._renderEffect.setVector3("eyePosition", camera2.globalPosition);
}
if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
var invView = viewMatrix.clone();
invView.invert();
this._renderEffect.setMatrix("invView", invView);
BABYLON2.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
}
if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
this._imageProcessingConfiguration.bind(this._renderEffect);
}
switch (this.blendMode) {
case BABYLON2.ParticleSystem.BLENDMODE_ADD:
this._engine.setAlphaMode(BABYLON2.Engine.ALPHA_ADD);
break;
case BABYLON2.ParticleSystem.BLENDMODE_ONEONE:
this._engine.setAlphaMode(BABYLON2.Engine.ALPHA_ONEONE);
break;
case BABYLON2.ParticleSystem.BLENDMODE_STANDARD:
this._engine.setAlphaMode(BABYLON2.Engine.ALPHA_COMBINE);
break;
case BABYLON2.ParticleSystem.BLENDMODE_MULTIPLY:
this._engine.setAlphaMode(BABYLON2.Engine.ALPHA_MULTIPLY);
break;
}
if (this.forceDepthWrite) {
this._engine.setDepthWrite(true);
}
this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
this._engine.drawArraysType(BABYLON2.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
this._engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
}
this._targetIndex++;
if (this._targetIndex === 2) {
this._targetIndex = 0;
}
var tmpBuffer = this._sourceBuffer;
this._sourceBuffer = this._targetBuffer;
this._targetBuffer = tmpBuffer;
return this._currentActiveCount;
};
GPUParticleSystem2.prototype.rebuild = function() {
this._initialize(true);
};
GPUParticleSystem2.prototype._releaseBuffers = function() {
if (this._buffer0) {
this._buffer0.dispose();
this._buffer0 = null;
}
if (this._buffer1) {
this._buffer1.dispose();
this._buffer1 = null;
}
if (this._spriteBuffer) {
this._spriteBuffer.dispose();
this._spriteBuffer = null;
}
};
GPUParticleSystem2.prototype._releaseVAOs = function() {
if (!this._updateVAO) {
return;
}
for (var index = 0; index < this._updateVAO.length; index++) {
this._engine.releaseVertexArrayObject(this._updateVAO[index]);
}
this._updateVAO = [];
for (var index = 0; index < this._renderVAO.length; index++) {
this._engine.releaseVertexArrayObject(this._renderVAO[index]);
}
this._renderVAO = [];
};
GPUParticleSystem2.prototype.dispose = function(disposeTexture) {
if (disposeTexture === void 0) {
disposeTexture = true;
}
var index = this._scene.particleSystems.indexOf(this);
if (index > -1) {
this._scene.particleSystems.splice(index, 1);
}
this._releaseBuffers();
this._releaseVAOs();
if (this._colorGradientsTexture) {
this._colorGradientsTexture.dispose();
this._colorGradientsTexture = null;
}
if (this._sizeGradientsTexture) {
this._sizeGradientsTexture.dispose();
this._sizeGradientsTexture = null;
}
if (this._angularSpeedGradientsTexture) {
this._angularSpeedGradientsTexture.dispose();
this._angularSpeedGradientsTexture = null;
}
if (this._velocityGradientsTexture) {
this._velocityGradientsTexture.dispose();
this._velocityGradientsTexture = null;
}
if (this._limitVelocityGradientsTexture) {
this._limitVelocityGradientsTexture.dispose();
this._limitVelocityGradientsTexture = null;
}
if (this._dragGradientsTexture) {
this._dragGradientsTexture.dispose();
this._dragGradientsTexture = null;
}
if (this._randomTexture) {
this._randomTexture.dispose();
this._randomTexture = null;
}
if (this._randomTexture2) {
this._randomTexture2.dispose();
this._randomTexture2 = null;
}
if (disposeTexture && this.particleTexture) {
this.particleTexture.dispose();
this.particleTexture = null;
}
if (disposeTexture && this.noiseTexture) {
this.noiseTexture.dispose();
this.noiseTexture = null;
}
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
};
GPUParticleSystem2.prototype.clone = function(name, newEmitter) {
var result = new GPUParticleSystem2(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
BABYLON2.Tools.DeepCopy(this, result);
if (newEmitter === void 0) {
newEmitter = this.emitter;
}
result.emitter = newEmitter;
if (this.particleTexture) {
result.particleTexture = new BABYLON2.Texture(this.particleTexture.url, this._scene);
}
return result;
};
GPUParticleSystem2.prototype.serialize = function() {
var serializationObject = {};
BABYLON2.ParticleSystem._Serialize(serializationObject, this);
serializationObject.activeParticleCount = this.activeParticleCount;
return serializationObject;
};
GPUParticleSystem2.Parse = function(parsedParticleSystem, scene, rootUrl, doNotStart) {
if (doNotStart === void 0) {
doNotStart = false;
}
var name = parsedParticleSystem.name;
var particleSystem = new GPUParticleSystem2(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
if (parsedParticleSystem.activeParticleCount) {
particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
}
BABYLON2.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
if (parsedParticleSystem.preventAutoStart) {
particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
}
if (!doNotStart && !particleSystem.preventAutoStart) {
particleSystem.start();
}
return particleSystem;
};
return GPUParticleSystem2;
}(BABYLON2.BaseParticleSystem)
);
BABYLON2.GPUParticleSystem = GPUParticleSystem;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SolidParticle = (
/** @class */
function() {
function SolidParticle2(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
if (modelBoundingInfo === void 0) {
modelBoundingInfo = null;
}
this.idx = 0;
this.color = new BABYLON2.Color4(1, 1, 1, 1);
this.position = BABYLON2.Vector3.Zero();
this.rotation = BABYLON2.Vector3.Zero();
this.scaling = BABYLON2.Vector3.One();
this.uvs = new BABYLON2.Vector4(0, 0, 1, 1);
this.velocity = BABYLON2.Vector3.Zero();
this.pivot = BABYLON2.Vector3.Zero();
this.translateFromPivot = false;
this.alive = true;
this.isVisible = true;
this._pos = 0;
this._ind = 0;
this.shapeId = 0;
this.idxInShape = 0;
this._stillInvisible = false;
this._rotationMatrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
this.parentId = null;
this._globalPosition = BABYLON2.Vector3.Zero();
this.idx = particleIndex;
this._pos = positionIndex;
this._ind = indiceIndex;
this._model = model;
this.shapeId = shapeId;
this.idxInShape = idxInShape;
this._sps = sps;
if (modelBoundingInfo) {
this._modelBoundingInfo = modelBoundingInfo;
this._boundingInfo = new BABYLON2.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
}
}
Object.defineProperty(SolidParticle2.prototype, "scale", {
/**
* Legacy support, changed scale to scaling
*/
get: function() {
return this.scaling;
},
/**
* Legacy support, changed scale to scaling
*/
set: function(scale) {
this.scaling = scale;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticle2.prototype, "quaternion", {
/**
* Legacy support, changed quaternion to rotationQuaternion
*/
get: function() {
return this.rotationQuaternion;
},
/**
* Legacy support, changed quaternion to rotationQuaternion
*/
set: function(q) {
this.rotationQuaternion = q;
},
enumerable: true,
configurable: true
});
SolidParticle2.prototype.intersectsMesh = function(target) {
if (!this._boundingInfo || !target._boundingInfo) {
return false;
}
if (this._sps._bSphereOnly) {
return BABYLON2.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
}
return this._boundingInfo.intersects(target._boundingInfo, false);
};
return SolidParticle2;
}()
);
BABYLON2.SolidParticle = SolidParticle;
var ModelShape = (
/** @class */
function() {
function ModelShape2(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
this._indicesLength = 0;
this.shapeID = id;
this._shape = shape;
this._indicesLength = indicesLength;
this._shapeUV = shapeUV;
this._positionFunction = posFunction;
this._vertexFunction = vtxFunction;
}
return ModelShape2;
}()
);
BABYLON2.ModelShape = ModelShape;
var DepthSortedParticle = (
/** @class */
function() {
function DepthSortedParticle2() {
this.ind = 0;
this.indicesLength = 0;
this.sqDistance = 0;
}
return DepthSortedParticle2;
}()
);
BABYLON2.DepthSortedParticle = DepthSortedParticle;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SolidParticleSystem = (
/** @class */
function() {
function SolidParticleSystem2(name, scene, options) {
this.particles = new Array();
this.nbParticles = 0;
this.billboard = false;
this.recomputeNormals = true;
this.counter = 0;
this.vars = {};
this._bSphereOnly = false;
this._bSphereRadiusFactor = 1;
this._positions = new Array();
this._indices = new Array();
this._normals = new Array();
this._colors = new Array();
this._uvs = new Array();
this._index = 0;
this._updatable = true;
this._pickable = false;
this._isVisibilityBoxLocked = false;
this._alwaysVisible = false;
this._depthSort = false;
this._shapeCounter = 0;
this._copy = new BABYLON2.SolidParticle(0, 0, 0, null, 0, 0, this);
this._color = new BABYLON2.Color4(0, 0, 0, 0);
this._computeParticleColor = true;
this._computeParticleTexture = true;
this._computeParticleRotation = true;
this._computeParticleVertex = false;
this._computeBoundingBox = false;
this._depthSortParticles = true;
this._cam_axisZ = BABYLON2.Vector3.Zero();
this._cam_axisY = BABYLON2.Vector3.Zero();
this._cam_axisX = BABYLON2.Vector3.Zero();
this._axisZ = BABYLON2.Axis.Z;
this._camDir = BABYLON2.Vector3.Zero();
this._camInvertedPosition = BABYLON2.Vector3.Zero();
this._rotMatrix = new BABYLON2.Matrix();
this._invertMatrix = new BABYLON2.Matrix();
this._rotated = BABYLON2.Vector3.Zero();
this._quaternion = new BABYLON2.Quaternion();
this._vertex = BABYLON2.Vector3.Zero();
this._normal = BABYLON2.Vector3.Zero();
this._yaw = 0;
this._pitch = 0;
this._roll = 0;
this._halfroll = 0;
this._halfpitch = 0;
this._halfyaw = 0;
this._sinRoll = 0;
this._cosRoll = 0;
this._sinPitch = 0;
this._cosPitch = 0;
this._sinYaw = 0;
this._cosYaw = 0;
this._mustUnrotateFixedNormals = false;
this._minimum = BABYLON2.Vector3.Zero();
this._maximum = BABYLON2.Vector3.Zero();
this._minBbox = BABYLON2.Vector3.Zero();
this._maxBbox = BABYLON2.Vector3.Zero();
this._particlesIntersect = false;
this._depthSortFunction = function(p1, p2) {
return p2.sqDistance - p1.sqDistance;
};
this._needs32Bits = false;
this._pivotBackTranslation = BABYLON2.Vector3.Zero();
this._scaledPivot = BABYLON2.Vector3.Zero();
this._particleHasParent = false;
this.name = name;
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
this._camera = scene.activeCamera;
this._pickable = options ? options.isPickable : false;
this._depthSort = options ? options.enableDepthSort : false;
this._particlesIntersect = options ? options.particleIntersection : false;
this._bSphereOnly = options ? options.boundingSphereOnly : false;
this._bSphereRadiusFactor = options && options.bSphereRadiusFactor ? options.bSphereRadiusFactor : 1;
if (options && options.updatable !== void 0) {
this._updatable = options.updatable;
} else {
this._updatable = true;
}
if (this._pickable) {
this.pickedParticles = [];
}
if (this._depthSort) {
this.depthSortedParticles = [];
}
}
SolidParticleSystem2.prototype.buildMesh = function() {
if (this.nbParticles === 0) {
var triangle = BABYLON2.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
this.addShape(triangle, 1);
triangle.dispose();
}
this._indices32 = this._needs32Bits ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
this._positions32 = new Float32Array(this._positions);
this._uvs32 = new Float32Array(this._uvs);
this._colors32 = new Float32Array(this._colors);
if (this.recomputeNormals) {
BABYLON2.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
}
this._normals32 = new Float32Array(this._normals);
this._fixedNormal32 = new Float32Array(this._normals);
if (this._mustUnrotateFixedNormals) {
this._unrotateFixedNormals();
}
var vertexData = new BABYLON2.VertexData();
vertexData.indices = this._depthSort ? this._indices : this._indices32;
vertexData.set(this._positions32, BABYLON2.VertexBuffer.PositionKind);
vertexData.set(this._normals32, BABYLON2.VertexBuffer.NormalKind);
if (this._uvs32.length > 0) {
vertexData.set(this._uvs32, BABYLON2.VertexBuffer.UVKind);
}
if (this._colors32.length > 0) {
vertexData.set(this._colors32, BABYLON2.VertexBuffer.ColorKind);
}
var mesh2 = new BABYLON2.Mesh(this.name, this._scene);
vertexData.applyToMesh(mesh2, this._updatable);
this.mesh = mesh2;
this.mesh.isPickable = this._pickable;
if (!this._depthSort) {
this._indices = null;
}
this._positions = null;
this._normals = null;
this._uvs = null;
this._colors = null;
if (!this._updatable) {
this.particles.length = 0;
}
return mesh2;
};
SolidParticleSystem2.prototype.digest = function(mesh2, options) {
var size = options && options.facetNb || 1;
var number = options && options.number || 0;
var delta = options && options.delta || 0;
var meshPos = mesh2.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var meshInd = mesh2.getIndices();
var meshUV = mesh2.getVerticesData(BABYLON2.VertexBuffer.UVKind);
var meshCol = mesh2.getVerticesData(BABYLON2.VertexBuffer.ColorKind);
var meshNor = mesh2.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var f = 0;
var totalFacets = meshInd.length / 3;
if (number) {
number = number > totalFacets ? totalFacets : number;
size = Math.round(totalFacets / number);
delta = 0;
} else {
size = size > totalFacets ? totalFacets : size;
}
var facetPos = [];
var facetInd = [];
var facetUV = [];
var facetCol = [];
var barycenter = BABYLON2.Vector3.Zero();
var sizeO = size;
while (f < totalFacets) {
size = sizeO + Math.floor((1 + delta) * Math.random());
if (f > totalFacets - size) {
size = totalFacets - f;
}
facetPos.length = 0;
facetInd.length = 0;
facetUV.length = 0;
facetCol.length = 0;
var fi = 0;
for (var j = f * 3; j < (f + size) * 3; j++) {
facetInd.push(fi);
var i2 = meshInd[j];
facetPos.push(meshPos[i2 * 3], meshPos[i2 * 3 + 1], meshPos[i2 * 3 + 2]);
if (meshUV) {
facetUV.push(meshUV[i2 * 2], meshUV[i2 * 2 + 1]);
}
if (meshCol) {
facetCol.push(meshCol[i2 * 4], meshCol[i2 * 4 + 1], meshCol[i2 * 4 + 2], meshCol[i2 * 4 + 3]);
}
fi++;
}
var idx = this.nbParticles;
var shape = this._posToShape(facetPos);
var shapeUV = this._uvsToShapeUV(facetUV);
var v;
for (v = 0; v < shape.length; v++) {
barycenter.addInPlace(shape[v]);
}
barycenter.scaleInPlace(1 / shape.length);
for (v = 0; v < shape.length; v++) {
shape[v].subtractInPlace(barycenter);
}
var bInfo;
if (this._particlesIntersect) {
bInfo = new BABYLON2.BoundingInfo(barycenter, barycenter);
}
var modelShape = new BABYLON2.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
var currentPos = this._positions.length;
var currentInd = this._indices.length;
this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
this.particles[this.nbParticles].position.addInPlace(barycenter);
this._index += shape.length;
idx++;
this.nbParticles++;
this._shapeCounter++;
f += size;
}
return this;
};
SolidParticleSystem2.prototype._unrotateFixedNormals = function() {
var index = 0;
var idx = 0;
for (var p = 0; p < this.particles.length; p++) {
this._particle = this.particles[p];
this._shape = this._particle._model._shape;
if (this._particle.rotationQuaternion) {
this._quaternion.copyFrom(this._particle.rotationQuaternion);
} else {
this._yaw = this._particle.rotation.y;
this._pitch = this._particle.rotation.x;
this._roll = this._particle.rotation.z;
this._quaternionRotationYPR();
}
this._quaternionToRotationMatrix();
this._rotMatrix.invertToRef(this._invertMatrix);
for (var pt = 0; pt < this._shape.length; pt++) {
idx = index + pt * 3;
BABYLON2.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
this._fixedNormal32[idx] = this._normal.x;
this._fixedNormal32[idx + 1] = this._normal.y;
this._fixedNormal32[idx + 2] = this._normal.z;
}
index = idx + 3;
}
};
SolidParticleSystem2.prototype._resetCopy = function() {
this._copy.position.x = 0;
this._copy.position.y = 0;
this._copy.position.z = 0;
this._copy.rotation.x = 0;
this._copy.rotation.y = 0;
this._copy.rotation.z = 0;
this._copy.rotationQuaternion = null;
this._copy.scaling.x = 1;
this._copy.scaling.y = 1;
this._copy.scaling.z = 1;
this._copy.uvs.x = 0;
this._copy.uvs.y = 0;
this._copy.uvs.z = 1;
this._copy.uvs.w = 1;
this._copy.color = null;
this._copy.translateFromPivot = false;
};
SolidParticleSystem2.prototype._meshBuilder = function(p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
var i2;
var u = 0;
var c = 0;
var n = 0;
this._resetCopy();
if (options && options.positionFunction) {
options.positionFunction(this._copy, idx, idxInShape);
this._mustUnrotateFixedNormals = true;
}
if (this._copy.rotationQuaternion) {
this._quaternion.copyFrom(this._copy.rotationQuaternion);
} else {
this._yaw = this._copy.rotation.y;
this._pitch = this._copy.rotation.x;
this._roll = this._copy.rotation.z;
this._quaternionRotationYPR();
}
this._quaternionToRotationMatrix();
this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
if (this._copy.translateFromPivot) {
this._pivotBackTranslation.copyFromFloats(0, 0, 0);
} else {
this._pivotBackTranslation.copyFrom(this._scaledPivot);
}
for (i2 = 0; i2 < shape.length; i2++) {
this._vertex.x = shape[i2].x;
this._vertex.y = shape[i2].y;
this._vertex.z = shape[i2].z;
if (options && options.vertexFunction) {
options.vertexFunction(this._copy, this._vertex, i2);
}
this._vertex.x *= this._copy.scaling.x;
this._vertex.y *= this._copy.scaling.y;
this._vertex.z *= this._copy.scaling.z;
this._vertex.x -= this._scaledPivot.x;
this._vertex.y -= this._scaledPivot.y;
this._vertex.z -= this._scaledPivot.z;
BABYLON2.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
this._rotated.addInPlace(this._pivotBackTranslation);
positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
if (meshUV) {
uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
u += 2;
}
if (this._copy.color) {
this._color = this._copy.color;
} else if (meshCol && meshCol[c] !== void 0) {
this._color.r = meshCol[c];
this._color.g = meshCol[c + 1];
this._color.b = meshCol[c + 2];
this._color.a = meshCol[c + 3];
} else {
this._color.r = 1;
this._color.g = 1;
this._color.b = 1;
this._color.a = 1;
}
colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
c += 4;
if (!this.recomputeNormals && meshNor) {
this._normal.x = meshNor[n];
this._normal.y = meshNor[n + 1];
this._normal.z = meshNor[n + 2];
BABYLON2.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
normals.push(this._normal.x, this._normal.y, this._normal.z);
n += 3;
}
}
for (i2 = 0; i2 < meshInd.length; i2++) {
var current_ind = p + meshInd[i2];
indices.push(current_ind);
if (current_ind > 65535) {
this._needs32Bits = true;
}
}
if (this._pickable) {
var nbfaces = meshInd.length / 3;
for (i2 = 0; i2 < nbfaces; i2++) {
this.pickedParticles.push({ idx, faceId: i2 });
}
}
if (this._depthSort) {
this.depthSortedParticles.push(new BABYLON2.DepthSortedParticle());
}
return this._copy;
};
SolidParticleSystem2.prototype._posToShape = function(positions) {
var shape = [];
for (var i2 = 0; i2 < positions.length; i2 += 3) {
shape.push(new BABYLON2.Vector3(positions[i2], positions[i2 + 1], positions[i2 + 2]));
}
return shape;
};
SolidParticleSystem2.prototype._uvsToShapeUV = function(uvs) {
var shapeUV = [];
if (uvs) {
for (var i2 = 0; i2 < uvs.length; i2++) {
shapeUV.push(uvs[i2]);
}
}
return shapeUV;
};
SolidParticleSystem2.prototype._addParticle = function(idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
if (bInfo === void 0) {
bInfo = null;
}
var sp = new BABYLON2.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
this.particles.push(sp);
return sp;
};
SolidParticleSystem2.prototype.addShape = function(mesh2, nb, options) {
var meshPos = mesh2.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var meshInd = mesh2.getIndices();
var meshUV = mesh2.getVerticesData(BABYLON2.VertexBuffer.UVKind);
var meshCol = mesh2.getVerticesData(BABYLON2.VertexBuffer.ColorKind);
var meshNor = mesh2.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var bbInfo;
if (this._particlesIntersect) {
bbInfo = mesh2.getBoundingInfo();
}
var shape = this._posToShape(meshPos);
var shapeUV = this._uvsToShapeUV(meshUV);
var posfunc = options ? options.positionFunction : null;
var vtxfunc = options ? options.vertexFunction : null;
var modelShape = new BABYLON2.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
var sp;
var currentCopy;
var idx = this.nbParticles;
for (var i2 = 0; i2 < nb; i2++) {
var currentPos = this._positions.length;
var currentInd = this._indices.length;
currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i2, options);
if (this._updatable) {
sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i2, bbInfo);
sp.position.copyFrom(currentCopy.position);
sp.rotation.copyFrom(currentCopy.rotation);
if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
}
if (currentCopy.color && sp.color) {
sp.color.copyFrom(currentCopy.color);
}
sp.scaling.copyFrom(currentCopy.scaling);
sp.uvs.copyFrom(currentCopy.uvs);
}
this._index += shape.length;
idx++;
}
this.nbParticles += nb;
this._shapeCounter++;
return this._shapeCounter - 1;
};
SolidParticleSystem2.prototype._rebuildParticle = function(particle) {
this._resetCopy();
if (particle._model._positionFunction) {
particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
}
if (this._copy.rotationQuaternion) {
this._quaternion.copyFrom(this._copy.rotationQuaternion);
} else {
this._yaw = this._copy.rotation.y;
this._pitch = this._copy.rotation.x;
this._roll = this._copy.rotation.z;
this._quaternionRotationYPR();
}
this._quaternionToRotationMatrix();
this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
if (this._copy.translateFromPivot) {
this._pivotBackTranslation.copyFromFloats(0, 0, 0);
} else {
this._pivotBackTranslation.copyFrom(this._scaledPivot);
}
this._shape = particle._model._shape;
for (var pt = 0; pt < this._shape.length; pt++) {
this._vertex.x = this._shape[pt].x;
this._vertex.y = this._shape[pt].y;
this._vertex.z = this._shape[pt].z;
if (particle._model._vertexFunction) {
particle._model._vertexFunction(this._copy, this._vertex, pt);
}
this._vertex.x *= this._copy.scaling.x;
this._vertex.y *= this._copy.scaling.y;
this._vertex.z *= this._copy.scaling.z;
this._vertex.x -= this._scaledPivot.x;
this._vertex.y -= this._scaledPivot.y;
this._vertex.z -= this._scaledPivot.z;
BABYLON2.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
this._rotated.addInPlace(this._pivotBackTranslation);
this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
}
particle.position.x = 0;
particle.position.y = 0;
particle.position.z = 0;
particle.rotation.x = 0;
particle.rotation.y = 0;
particle.rotation.z = 0;
particle.rotationQuaternion = null;
particle.scaling.x = 1;
particle.scaling.y = 1;
particle.scaling.z = 1;
particle.uvs.x = 0;
particle.uvs.y = 0;
particle.uvs.z = 1;
particle.uvs.w = 1;
particle.pivot.x = 0;
particle.pivot.y = 0;
particle.pivot.z = 0;
particle.translateFromPivot = false;
particle.parentId = null;
};
SolidParticleSystem2.prototype.rebuildMesh = function() {
for (var p = 0; p < this.particles.length; p++) {
this._rebuildParticle(this.particles[p]);
}
this.mesh.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, this._positions32, false, false);
return this;
};
SolidParticleSystem2.prototype.setParticles = function(start, end, update) {
if (start === void 0) {
start = 0;
}
if (end === void 0) {
end = this.nbParticles - 1;
}
if (update === void 0) {
update = true;
}
if (!this._updatable) {
return this;
}
this.beforeUpdateParticles(start, end, update);
this._cam_axisX.x = 1;
this._cam_axisX.y = 0;
this._cam_axisX.z = 0;
this._cam_axisY.x = 0;
this._cam_axisY.y = 1;
this._cam_axisY.z = 0;
this._cam_axisZ.x = 0;
this._cam_axisZ.y = 0;
this._cam_axisZ.z = 1;
if (this.billboard || this._depthSort) {
this.mesh.computeWorldMatrix(true);
this.mesh._worldMatrix.invertToRef(this._invertMatrix);
}
if (this.billboard) {
this._camera.getDirectionToRef(this._axisZ, this._camDir);
BABYLON2.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
this._cam_axisZ.normalize();
var view = this._camera.getViewMatrix(true);
BABYLON2.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
BABYLON2.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
this._cam_axisY.normalize();
this._cam_axisX.normalize();
}
if (this._depthSort) {
BABYLON2.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition);
}
BABYLON2.Matrix.IdentityToRef(this._rotMatrix);
var idx = 0;
var index = 0;
var colidx = 0;
var colorIndex = 0;
var uvidx = 0;
var uvIndex = 0;
var pt = 0;
if (this.mesh.isFacetDataEnabled) {
this._computeBoundingBox = true;
}
end = end >= this.nbParticles ? this.nbParticles - 1 : end;
if (this._computeBoundingBox) {
if (start == 0 && end == this.nbParticles - 1) {
BABYLON2.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
BABYLON2.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
} else {
if (this.mesh._boundingInfo) {
this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
}
}
}
index = this.particles[start]._pos;
var vpos = index / 3 | 0;
colorIndex = vpos * 4;
uvIndex = vpos * 2;
for (var p = start; p <= end; p++) {
this._particle = this.particles[p];
this._shape = this._particle._model._shape;
this._shapeUV = this._particle._model._shapeUV;
this.updateParticle(this._particle);
if (this._depthSort && this._depthSortParticles) {
var dsp = this.depthSortedParticles[p];
dsp.ind = this._particle._ind;
dsp.indicesLength = this._particle._model._indicesLength;
dsp.sqDistance = BABYLON2.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
}
if (!this._particle.alive || this._particle._stillInvisible && !this._particle.isVisible) {
pt = this._shape.length;
index += pt * 3;
colorIndex += pt * 4;
uvIndex += pt * 2;
continue;
}
if (this._particle.isVisible) {
this._particle._stillInvisible = false;
this._particleHasParent = this._particle.parentId !== null;
this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
if (this.billboard) {
this._particle.rotation.x = 0;
this._particle.rotation.y = 0;
}
if (this._computeParticleRotation || this.billboard) {
if (this._particle.rotationQuaternion) {
this._quaternion.copyFrom(this._particle.rotationQuaternion);
} else {
this._yaw = this._particle.rotation.y;
this._pitch = this._particle.rotation.x;
this._roll = this._particle.rotation.z;
this._quaternionRotationYPR();
}
this._quaternionToRotationMatrix();
}
if (this._particleHasParent) {
this._parent = this.particles[this._particle.parentId];
this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
if (this._computeParticleRotation || this.billboard) {
this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
}
} else {
this._particle._globalPosition.x = this._particle.position.x;
this._particle._globalPosition.y = this._particle.position.y;
this._particle._globalPosition.z = this._particle.position.z;
if (this._computeParticleRotation || this.billboard) {
this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
}
}
if (this._particle.translateFromPivot) {
this._pivotBackTranslation.x = 0;
this._pivotBackTranslation.y = 0;
this._pivotBackTranslation.z = 0;
} else {
this._pivotBackTranslation.x = this._scaledPivot.x;
this._pivotBackTranslation.y = this._scaledPivot.y;
this._pivotBackTranslation.z = this._scaledPivot.z;
}
for (pt = 0; pt < this._shape.length; pt++) {
idx = index + pt * 3;
colidx = colorIndex + pt * 4;
uvidx = uvIndex + pt * 2;
this._vertex.x = this._shape[pt].x;
this._vertex.y = this._shape[pt].y;
this._vertex.z = this._shape[pt].z;
if (this._computeParticleVertex) {
this.updateParticleVertex(this._particle, this._vertex, pt);
}
this._vertex.x *= this._particle.scaling.x;
this._vertex.y *= this._particle.scaling.y;
this._vertex.z *= this._particle.scaling.z;
this._vertex.x -= this._scaledPivot.x;
this._vertex.y -= this._scaledPivot.y;
this._vertex.z -= this._scaledPivot.z;
this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
this._rotated.x += this._pivotBackTranslation.x;
this._rotated.y += this._pivotBackTranslation.y;
this._rotated.z += this._pivotBackTranslation.z;
this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
if (this._computeBoundingBox) {
if (this._positions32[idx] < this._minimum.x) {
this._minimum.x = this._positions32[idx];
}
if (this._positions32[idx] > this._maximum.x) {
this._maximum.x = this._positions32[idx];
}
if (this._positions32[idx + 1] < this._minimum.y) {
this._minimum.y = this._positions32[idx + 1];
}
if (this._positions32[idx + 1] > this._maximum.y) {
this._maximum.y = this._positions32[idx + 1];
}
if (this._positions32[idx + 2] < this._minimum.z) {
this._minimum.z = this._positions32[idx + 2];
}
if (this._positions32[idx + 2] > this._maximum.z) {
this._maximum.z = this._positions32[idx + 2];
}
}
if (!this._computeParticleVertex) {
this._normal.x = this._fixedNormal32[idx];
this._normal.y = this._fixedNormal32[idx + 1];
this._normal.z = this._fixedNormal32[idx + 2];
this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
}
if (this._computeParticleColor && this._particle.color) {
this._colors32[colidx] = this._particle.color.r;
this._colors32[colidx + 1] = this._particle.color.g;
this._colors32[colidx + 2] = this._particle.color.b;
this._colors32[colidx + 3] = this._particle.color.a;
}
if (this._computeParticleTexture) {
this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
}
}
} else {
this._particle._stillInvisible = true;
for (pt = 0; pt < this._shape.length; pt++) {
idx = index + pt * 3;
colidx = colorIndex + pt * 4;
uvidx = uvIndex + pt * 2;
this._positions32[idx] = 0;
this._positions32[idx + 1] = 0;
this._positions32[idx + 2] = 0;
this._normals32[idx] = 0;
this._normals32[idx + 1] = 0;
this._normals32[idx + 2] = 0;
if (this._computeParticleColor && this._particle.color) {
this._colors32[colidx] = this._particle.color.r;
this._colors32[colidx + 1] = this._particle.color.g;
this._colors32[colidx + 2] = this._particle.color.b;
this._colors32[colidx + 3] = this._particle.color.a;
}
if (this._computeParticleTexture) {
this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
}
}
}
if (this._particlesIntersect) {
var bInfo = this._particle._boundingInfo;
var bBox = bInfo.boundingBox;
var bSphere = bInfo.boundingSphere;
if (!this._bSphereOnly) {
for (var b2 = 0; b2 < bBox.vectors.length; b2++) {
this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b2].x * this._particle.scaling.x;
this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b2].y * this._particle.scaling.y;
this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b2].z * this._particle.scaling.z;
this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
bBox.vectors[b2].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
bBox.vectors[b2].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
bBox.vectors[b2].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
}
bBox._update(this.mesh._worldMatrix);
}
this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
bSphere._update(this.mesh._worldMatrix);
}
index = idx + 3;
colorIndex = colidx + 4;
uvIndex = uvidx + 2;
}
if (update) {
if (this._computeParticleColor) {
this.mesh.updateVerticesData(BABYLON2.VertexBuffer.ColorKind, this._colors32, false, false);
}
if (this._computeParticleTexture) {
this.mesh.updateVerticesData(BABYLON2.VertexBuffer.UVKind, this._uvs32, false, false);
}
this.mesh.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, this._positions32, false, false);
if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
BABYLON2.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
for (var i2 = 0; i2 < this._normals32.length; i2++) {
this._fixedNormal32[i2] = this._normals32[i2];
}
}
if (!this.mesh.areNormalsFrozen) {
this.mesh.updateVerticesData(BABYLON2.VertexBuffer.NormalKind, this._normals32, false, false);
}
}
if (this._depthSort && this._depthSortParticles) {
this.depthSortedParticles.sort(this._depthSortFunction);
var dspl = this.depthSortedParticles.length;
var sorted = 0;
var lind = 0;
var sind = 0;
var sid = 0;
for (sorted = 0; sorted < dspl; sorted++) {
lind = this.depthSortedParticles[sorted].indicesLength;
sind = this.depthSortedParticles[sorted].ind;
for (var i2 = 0; i2 < lind; i2++) {
this._indices32[sid] = this._indices[sind + i2];
sid++;
}
}
this.mesh.updateIndices(this._indices32);
}
}
if (this._computeBoundingBox) {
this.mesh._boundingInfo = new BABYLON2.BoundingInfo(this._minimum, this._maximum);
this.mesh._boundingInfo.update(this.mesh._worldMatrix);
}
this.afterUpdateParticles(start, end, update);
return this;
};
SolidParticleSystem2.prototype._quaternionRotationYPR = function() {
this._halfroll = this._roll * 0.5;
this._halfpitch = this._pitch * 0.5;
this._halfyaw = this._yaw * 0.5;
this._sinRoll = Math.sin(this._halfroll);
this._cosRoll = Math.cos(this._halfroll);
this._sinPitch = Math.sin(this._halfpitch);
this._cosPitch = Math.cos(this._halfpitch);
this._sinYaw = Math.sin(this._halfyaw);
this._cosYaw = Math.cos(this._halfyaw);
this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
};
SolidParticleSystem2.prototype._quaternionToRotationMatrix = function() {
this._rotMatrix.m[0] = 1 - 2 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z);
this._rotMatrix.m[1] = 2 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
this._rotMatrix.m[2] = 2 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
this._rotMatrix.m[3] = 0;
this._rotMatrix.m[4] = 2 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
this._rotMatrix.m[5] = 1 - 2 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x);
this._rotMatrix.m[6] = 2 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
this._rotMatrix.m[7] = 0;
this._rotMatrix.m[8] = 2 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
this._rotMatrix.m[9] = 2 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
this._rotMatrix.m[10] = 1 - 2 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x);
this._rotMatrix.m[11] = 0;
this._rotMatrix.m[12] = 0;
this._rotMatrix.m[13] = 0;
this._rotMatrix.m[14] = 0;
this._rotMatrix.m[15] = 1;
};
SolidParticleSystem2.prototype.dispose = function() {
this.mesh.dispose();
this.vars = null;
this._positions = null;
this._indices = null;
this._normals = null;
this._uvs = null;
this._colors = null;
this._indices32 = null;
this._positions32 = null;
this._normals32 = null;
this._fixedNormal32 = null;
this._uvs32 = null;
this._colors32 = null;
this.pickedParticles = null;
};
SolidParticleSystem2.prototype.refreshVisibleSize = function() {
if (!this._isVisibilityBoxLocked) {
this.mesh.refreshBoundingInfo();
}
return this;
};
SolidParticleSystem2.prototype.setVisibilityBox = function(size) {
var vis = size / 2;
this.mesh._boundingInfo = new BABYLON2.BoundingInfo(new BABYLON2.Vector3(-vis, -vis, -vis), new BABYLON2.Vector3(vis, vis, vis));
};
Object.defineProperty(SolidParticleSystem2.prototype, "isAlwaysVisible", {
/**
* Gets whether the SPS as always visible or not
* doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
*/
get: function() {
return this._alwaysVisible;
},
/**
* Sets the SPS as always visible or not
* doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
*/
set: function(val) {
this._alwaysVisible = val;
this.mesh.alwaysSelectAsActiveMesh = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticleSystem2.prototype, "isVisibilityBoxLocked", {
/**
* Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
* doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
*/
get: function() {
return this._isVisibilityBoxLocked;
},
/**
* Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
* doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
*/
set: function(val) {
this._isVisibilityBoxLocked = val;
var boundingInfo = this.mesh.getBoundingInfo();
boundingInfo.isLocked = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticleSystem2.prototype, "computeParticleRotation", {
/**
* Gets if `setParticles()` computes the particle rotations or not.
* Default value : true. The SPS is faster when it's set to false.
* Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
*/
get: function() {
return this._computeParticleRotation;
},
/**
* Tells to `setParticles()` to compute the particle rotations or not.
* Default value : true. The SPS is faster when it's set to false.
* Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
*/
set: function(val) {
this._computeParticleRotation = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticleSystem2.prototype, "computeParticleColor", {
/**
* Gets if `setParticles()` computes the particle colors or not.
* Default value : true. The SPS is faster when it's set to false.
* Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
*/
get: function() {
return this._computeParticleColor;
},
/**
* Tells to `setParticles()` to compute the particle colors or not.
* Default value : true. The SPS is faster when it's set to false.
* Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
*/
set: function(val) {
this._computeParticleColor = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticleSystem2.prototype, "computeParticleTexture", {
/**
* Gets if `setParticles()` computes the particle textures or not.
* Default value : true. The SPS is faster when it's set to false.
* Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
*/
get: function() {
return this._computeParticleTexture;
},
set: function(val) {
this._computeParticleTexture = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticleSystem2.prototype, "computeParticleVertex", {
/**
* Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
* Default value : false. The SPS is faster when it's set to false.
* Note : the particle custom vertex positions aren't stored values.
*/
get: function() {
return this._computeParticleVertex;
},
/**
* Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
* Default value : false. The SPS is faster when it's set to false.
* Note : the particle custom vertex positions aren't stored values.
*/
set: function(val) {
this._computeParticleVertex = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticleSystem2.prototype, "computeBoundingBox", {
/**
* Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
*/
get: function() {
return this._computeBoundingBox;
},
/**
* Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
*/
set: function(val) {
this._computeBoundingBox = val;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SolidParticleSystem2.prototype, "depthSortParticles", {
/**
* Gets if `setParticles()` sorts or not the distance between each particle and the camera.
* Skipped when `enableDepthSort` is set to `false` (default) at construction time.
* Default : `true`
*/
get: function() {
return this._depthSortParticles;
},
/**
* Tells to `setParticles()` to sort or not the distance between each particle and the camera.
* Skipped when `enableDepthSort` is set to `false` (default) at construction time.
* Default : `true`
*/
set: function(val) {
this._depthSortParticles = val;
},
enumerable: true,
configurable: true
});
SolidParticleSystem2.prototype.initParticles = function() {
};
SolidParticleSystem2.prototype.recycleParticle = function(particle) {
return particle;
};
SolidParticleSystem2.prototype.updateParticle = function(particle) {
return particle;
};
SolidParticleSystem2.prototype.updateParticleVertex = function(particle, vertex, pt) {
return vertex;
};
SolidParticleSystem2.prototype.beforeUpdateParticles = function(start, stop, update) {
};
SolidParticleSystem2.prototype.afterUpdateParticles = function(start, stop, update) {
};
return SolidParticleSystem2;
}()
);
BABYLON2.SolidParticleSystem = SolidParticleSystem;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MeshBuilder = (
/** @class */
function() {
function MeshBuilder2() {
}
MeshBuilder2.updateSideOrientation = function(orientation) {
if (orientation == BABYLON2.Mesh.DOUBLESIDE) {
return BABYLON2.Mesh.DOUBLESIDE;
}
if (orientation === void 0 || orientation === null) {
return BABYLON2.Mesh.FRONTSIDE;
}
return orientation;
};
MeshBuilder2.CreateBox = function(name, options, scene) {
if (scene === void 0) {
scene = null;
}
var box = new BABYLON2.Mesh(name, scene);
options.sideOrientation = MeshBuilder2.updateSideOrientation(options.sideOrientation);
box._originalBuilderSideOrientation = options.sideOrientation;
var vertexData = BABYLON2.VertexData.CreateBox(options);
vertexData.applyToMesh(box, options.updatable);
return box;
};
MeshBuilder2.CreateDisc = function(name, options, scene) {
if (scene === void 0) {
scene = null;
}
var disc = new BABYLON2.Mesh(name, scene);
options.sideOrientation = MeshBuilder2.updateSideOrientation(options.sideOrientation);
disc._originalBuilderSideOrientation = options.sideOrientation;
var vertexData = BABYLON2.VertexData.CreateDisc(options);
vertexData.applyToMesh(disc, options.updatable);
return disc;
};
MeshBuilder2.CreateRibbon = function(name, options, scene) {
if (scene === void 0) {
scene = null;
}
var pathArray = options.pathArray;
var closeArray = options.closeArray;
var closePath = options.closePath;
var sideOrientation = MeshBuilder2.updateSideOrientation(options.sideOrientation);
var instance = options.instance;
var updatable = options.updatable;
if (instance) {
BABYLON2.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON2.Tmp.Vector3[0]);
BABYLON2.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON2.Tmp.Vector3[1]);
var positionFunction = function(positions2) {
var minlg = pathArray[0].length;
var mesh2 = instance;
var i3 = 0;
var ns = mesh2._originalBuilderSideOrientation === BABYLON2.Mesh.DOUBLESIDE ? 2 : 1;
for (var si = 1; si <= ns; si++) {
for (var p2 = 0; p2 < pathArray.length; p2++) {
var path = pathArray[p2];
var l = path.length;
minlg = minlg < l ? minlg : l;
var j = 0;
while (j < minlg) {
positions2[i3] = path[j].x;
positions2[i3 + 1] = path[j].y;
positions2[i3 + 2] = path[j].z;
if (path[j].x < BABYLON2.Tmp.Vector3[0].x) {
BABYLON2.Tmp.Vector3[0].x = path[j].x;
}
if (path[j].x > BABYLON2.Tmp.Vector3[1].x) {
BABYLON2.Tmp.Vector3[1].x = path[j].x;
}
if (path[j].y < BABYLON2.Tmp.Vector3[0].y) {
BABYLON2.Tmp.Vector3[0].y = path[j].y;
}
if (path[j].y > BABYLON2.Tmp.Vector3[1].y) {
BABYLON2.Tmp.Vector3[1].y = path[j].y;
}
if (path[j].z < BABYLON2.Tmp.Vector3[0].z) {
BABYLON2.Tmp.Vector3[0].z = path[j].z;
}
if (path[j].z > BABYLON2.Tmp.Vector3[1].z) {
BABYLON2.Tmp.Vector3[1].z = path[j].z;
}
j++;
i3 += 3;
}
if (mesh2._creationDataStorage && mesh2._creationDataStorage.closePath) {
positions2[i3] = path[0].x;
positions2[i3 + 1] = path[0].y;
positions2[i3 + 2] = path[0].z;
i3 += 3;
}
}
}
};
var positions = instance.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
positionFunction(positions);
instance._boundingInfo = new BABYLON2.BoundingInfo(BABYLON2.Tmp.Vector3[2], BABYLON2.Tmp.Vector3[3]);
instance._boundingInfo.update(instance._worldMatrix);
instance.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, positions, false, false);
if (options.colors) {
var colors = instance.getVerticesData(BABYLON2.VertexBuffer.ColorKind);
for (var c = 0; c < options.colors.length; c++) {
colors[c * 4] = options.colors[c].r;
colors[c * 4 + 1] = options.colors[c].g;
colors[c * 4 + 2] = options.colors[c].b;
colors[c * 4 + 3] = options.colors[c].a;
}
instance.updateVerticesData(BABYLON2.VertexBuffer.ColorKind, colors, false, false);
}
if (options.uvs) {
var uvs = instance.getVerticesData(BABYLON2.VertexBuffer.UVKind);
for (var i2 = 0; i2 < options.uvs.length; i2++) {
uvs[i2 * 2] = options.uvs[i2].x;
uvs[i2 * 2 + 1] = options.uvs[i2].y;
}
instance.updateVerticesData(BABYLON2.VertexBuffer.UVKind, uvs, false, false);
}
if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
var indices = instance.getIndices();
var normals = instance.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
BABYLON2.VertexData.ComputeNormals(positions, indices, normals, params);
if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
var indexFirst = 0;
var indexLast = 0;
for (var p = 0; p < pathArray.length; p++) {
indexFirst = instance._creationDataStorage.idx[p] * 3;
if (p + 1 < pathArray.length) {
indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
} else {
indexLast = normals.length - 3;
}
normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
normals[indexLast] = normals[indexFirst];
normals[indexLast + 1] = normals[indexFirst + 1];
normals[indexLast + 2] = normals[indexFirst + 2];
}
}
if (!instance.areNormalsFrozen) {
instance.updateVerticesData(BABYLON2.VertexBuffer.NormalKind, normals, false, false);
}
}
return instance;
} else {
var ribbon = new BABYLON2.Mesh(name, scene);
ribbon._originalBuilderSideOrientation = sideOrientation;
ribbon._creationDataStorage = new BABYLON2._CreationDataStorage();
var vertexData = BABYLON2.VertexData.CreateRibbon(options);
if (closePath) {
ribbon._creationDataStorage.idx = vertexData._idx;
}
ribbon._creationDataStorage.closePath = closePath;
ribbon._creationDataStorage.closeArray = closeArray;
vertexData.applyToMesh(ribbon, updatable);
return ribbon;
}
};
MeshBuilder2.CreateCylinder = function(name, options, scene) {
var cylinder = new BABYLON2.Mesh(name, scene);
options.sideOrientation = MeshBuilder2.updateSideOrientation(options.sideOrientation);
cylinder._originalBuilderSideOrientation = options.sideOrientation;
var vertexData = BABYLON2.VertexData.CreateCylinder(options);
vertexData.applyToMesh(cylinder, options.updatable);
return cylinder;
};
MeshBuilder2.CreateLineSystem = function(name, options, scene) {
var instance = options.instance;
var lines = options.lines;
var colors = options.colors;
if (instance) {
var positions = instance.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var vertexColor;
var lineColors;
if (colors) {
vertexColor = instance.getVerticesData(BABYLON2.VertexBuffer.ColorKind);
}
var i2 = 0;
var c = 0;
for (var l = 0; l < lines.length; l++) {
var points = lines[l];
for (var p = 0; p < points.length; p++) {
positions[i2] = points[p].x;
positions[i2 + 1] = points[p].y;
positions[i2 + 2] = points[p].z;
if (colors && vertexColor) {
lineColors = colors[l];
vertexColor[c] = lineColors[p].r;
vertexColor[c + 1] = lineColors[p].g;
vertexColor[c + 2] = lineColors[p].b;
vertexColor[c + 3] = lineColors[p].a;
c += 4;
}
i2 += 3;
}
}
instance.updateVerticesData(BABYLON2.VertexBuffer.PositionKind, positions, false, false);
if (colors && vertexColor) {
instance.updateVerticesData(BABYLON2.VertexBuffer.ColorKind, vertexColor, false, false);
}
return instance;
}
var useVertexColor = colors ? true : false;
var lineSystem = new BABYLON2.LinesMesh(name, scene, null, void 0, void 0, useVertexColor, options.useVertexAlpha);
var vertexData = BABYLON2.VertexData.CreateLineSystem(options);
vertexData.applyToMesh(lineSystem, options.updatable);
return lineSystem;
};
MeshBuilder2.CreateLines = function(name, options, scene) {
if (scene === void 0) {
scene = null;
}
var colors = options.colors ? [options.colors] : null;
var lines = MeshBuilder2.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors, useVertexAlpha: options.useVertexAlpha }, scene);
return lines;
};
MeshBuilder2.CreateLathe = function(name, options, scene) {
var arc = options.arc ? options.arc <= 0 || options.arc > 1 ? 1 : options.arc : 1;
var closed = options.closed === void 0 ? true : options.closed;
var shape = options.shape;
var radius = options.radius || 1;
var tessellation = options.tessellation || 64;
var clip = options.clip || 0;
var updatable = options.updatable;
var sideOrientation = MeshBuilder2.updateSideOrientation(options.sideOrientation);
var cap = options.cap || BABYLON2.Mesh.NO_CAP;
var pi2 = Math.PI * 2;
var paths = new Array();
var invertUV = options.invertUV || false;
var i2 = 0;
var p = 0;
var step = pi2 / tessellation * arc;
var rotated;
var path = new Array();
for (i2 = 0; i2 <= tessellation - clip; i2++) {
var path = [];
if (cap == BABYLON2.Mesh.CAP_START || cap == BABYLON2.Mesh.CAP_ALL) {
path.push(new BABYLON2.Vector3(0, shape[0].y, 0));
path.push(new BABYLON2.Vector3(Math.cos(i2 * step) * shape[0].x * radius, shape[0].y, Math.sin(i2 * step) * shape[0].x * radius));
}
for (p = 0; p < shape.length; p++) {
rotated = new BABYLON2.Vector3(Math.cos(i2 * step) * shape[p].x * radius, shape[p].y, Math.sin(i2 * step) * shape[p].x * radius);
path.push(rotated);
}
if (cap == BABYLON2.Mesh.CAP_END || cap == BABYLON2.Mesh.CAP_ALL) {
path.push(new BABYLON2.Vector3(Math.cos(i2 * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i2 * step) * shape[shape.length - 1].x * radius));
path.push(new BABYLON2.Vector3(0, shape[shape.length - 1].y, 0));
}
paths.push(path);
}
var lathe = MeshBuilder2.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation, updatable, invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
return lathe;
};
MeshBuilder2.CreatePlane = function(name, options, scene) {
var plane = new BABYLON2.Mesh(name, scene);
options.sideOrientation = MeshBuilder2.updateSideOrientation(options.sideOrientation);
plane._originalBuilderSideOrientation = options.sideOrientation;
var vertexData = BABYLON2.VertexData.CreatePlane(options);
vertexData.applyToMesh(plane, options.updatable);
if (options.sourcePlane) {
plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
var product = Math.acos(BABYLON2.Vector3.Dot(options.sourcePlane.normal, BABYLON2.Axis.Z));
var vectorProduct = BABYLON2.Vector3.Cross(BABYLON2.Axis.Z, options.sourcePlane.normal);
if (vectorProduct.lengthSquared() > BABYLON2.Epsilon) {
plane.rotate(vectorProduct, product);
}
}
return plane;
};
return MeshBuilder2;
}()
);
BABYLON2.MeshBuilder = MeshBuilder;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DracoCompression = (
/** @class */
function() {
function DracoCompression2() {
}
Object.defineProperty(DracoCompression2, "DecoderAvailable", {
/**
* Returns true if the decoder is available.
*/
get: function() {
if (typeof DracoDecoderModule !== "undefined") {
return true;
}
var decoder = DracoCompression2.Configuration.decoder;
if (decoder) {
if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
return true;
}
if (decoder.fallbackUrl) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
DracoCompression2.prototype.dispose = function() {
};
DracoCompression2.prototype.decodeMeshAsync = function(data2, attributes) {
var dataView = data2 instanceof ArrayBuffer ? new Uint8Array(data2) : data2;
return DracoCompression2._GetDecoderModule().then(function(wrappedModule) {
var module = wrappedModule.module;
var vertexData = new BABYLON2.VertexData();
var buffer = new module.DecoderBuffer();
buffer.Init(dataView, dataView.byteLength);
var decoder = new module.Decoder();
var geometry;
var status;
try {
var type = decoder.GetEncodedGeometryType(buffer);
switch (type) {
case module.TRIANGULAR_MESH:
geometry = new module.Mesh();
status = decoder.DecodeBufferToMesh(buffer, geometry);
break;
case module.POINT_CLOUD:
geometry = new module.PointCloud();
status = decoder.DecodeBufferToPointCloud(buffer, geometry);
break;
default:
throw new Error("Invalid geometry type " + type);
}
if (!status.ok() || !geometry.ptr) {
throw new Error(status.error_msg());
}
var numPoints = geometry.num_points();
if (type === module.TRIANGULAR_MESH) {
var numFaces = geometry.num_faces();
var faceIndices = new module.DracoInt32Array();
try {
var indices = new Uint32Array(numFaces * 3);
for (var i2 = 0; i2 < numFaces; i2++) {
decoder.GetFaceFromMesh(geometry, i2, faceIndices);
var offset = i2 * 3;
indices[offset + 0] = faceIndices.GetValue(0);
indices[offset + 1] = faceIndices.GetValue(1);
indices[offset + 2] = faceIndices.GetValue(2);
}
vertexData.indices = indices;
} finally {
module.destroy(faceIndices);
}
}
for (var kind in attributes) {
var uniqueId = attributes[kind];
var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
var dracoData = new module.DracoFloat32Array();
try {
decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
var babylonData = new Float32Array(numPoints * attribute.num_components());
for (var i2 = 0; i2 < babylonData.length; i2++) {
babylonData[i2] = dracoData.GetValue(i2);
}
vertexData.set(babylonData, kind);
} finally {
module.destroy(dracoData);
}
}
} finally {
if (geometry) {
module.destroy(geometry);
}
module.destroy(decoder);
module.destroy(buffer);
}
return vertexData;
});
};
DracoCompression2._GetDecoderModule = function() {
if (!DracoCompression2._DecoderModulePromise) {
var promise = null;
var config_1 = {};
if (typeof DracoDecoderModule !== "undefined") {
promise = Promise.resolve();
} else {
var decoder = DracoCompression2.Configuration.decoder;
if (decoder) {
if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
promise = Promise.all([
DracoCompression2._LoadScriptAsync(decoder.wasmUrl),
DracoCompression2._LoadFileAsync(decoder.wasmBinaryUrl).then(function(data2) {
config_1.wasmBinary = data2;
})
]);
} else if (decoder.fallbackUrl) {
promise = DracoCompression2._LoadScriptAsync(decoder.fallbackUrl);
}
}
}
if (!promise) {
throw new Error("Draco decoder module is not available");
}
DracoCompression2._DecoderModulePromise = promise.then(function() {
return new Promise(function(resolve) {
config_1.onModuleLoaded = function(decoderModule) {
resolve({ module: decoderModule });
};
DracoDecoderModule(config_1);
});
});
}
return DracoCompression2._DecoderModulePromise;
};
DracoCompression2._LoadScriptAsync = function(url) {
return new Promise(function(resolve, reject) {
BABYLON2.Tools.LoadScript(url, function() {
resolve();
}, function(message) {
reject(new Error(message));
});
});
};
DracoCompression2._LoadFileAsync = function(url) {
return new Promise(function(resolve, reject) {
BABYLON2.Tools.LoadFile(url, function(data2) {
resolve(data2);
}, void 0, void 0, true, function(request, exception) {
reject(exception);
});
});
};
DracoCompression2.Configuration = {
decoder: {
wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
}
};
return DracoCompression2;
}()
);
BABYLON2.DracoCompression = DracoCompression;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Engine.AudioEngineFactory = function(hostElement) {
return new AudioEngine(hostElement);
};
var AudioEngine = (
/** @class */
function() {
function AudioEngine2(hostElement) {
if (hostElement === void 0) {
hostElement = null;
}
var _this = this;
this._audioContext = null;
this._audioContextInitialized = false;
this._muteButton = null;
this.canUseWebAudio = false;
this.WarnedWebAudioUnsupported = false;
this.isMP3supported = false;
this.isOGGsupported = false;
this.unlocked = true;
this.useCustomUnlockedButton = false;
this.onAudioUnlockedObservable = new BABYLON2.Observable();
this.onAudioLockedObservable = new BABYLON2.Observable();
this._tryToRun = false;
this._onResize = function() {
_this._moveButtonToTopLeft();
};
if (typeof window.AudioContext !== "undefined" || typeof window.webkitAudioContext !== "undefined") {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
this.canUseWebAudio = true;
}
var audioElem = document.createElement("audio");
this._hostElement = hostElement;
try {
if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, "")) {
this.isMP3supported = true;
}
} catch (e2) {
}
try {
if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, "")) {
this.isOGGsupported = true;
}
} catch (e2) {
}
}
Object.defineProperty(AudioEngine2.prototype, "audioContext", {
/**
* Gets the current AudioContext if available.
*/
get: function() {
if (!this._audioContextInitialized) {
this._initializeAudioContext();
} else {
if (!this.unlocked && !this._muteButton) {
this._displayMuteButton();
}
}
return this._audioContext;
},
enumerable: true,
configurable: true
});
AudioEngine2.prototype.lock = function() {
this._triggerSuspendedState();
};
AudioEngine2.prototype.unlock = function() {
this._triggerRunningState();
};
AudioEngine2.prototype._resumeAudioContext = function() {
var result;
if (this._audioContext.resume) {
result = this._audioContext.resume();
}
return result || Promise.resolve();
};
AudioEngine2.prototype._initializeAudioContext = function() {
try {
if (this.canUseWebAudio) {
this._audioContext = new AudioContext();
this.masterGain = this._audioContext.createGain();
this.masterGain.gain.value = 1;
this.masterGain.connect(this._audioContext.destination);
this._audioContextInitialized = true;
if (this._audioContext.state === "running") {
this._triggerRunningState();
}
}
} catch (e2) {
this.canUseWebAudio = false;
BABYLON2.Tools.Error("Web Audio: " + e2.message);
}
};
AudioEngine2.prototype._triggerRunningState = function() {
var _this = this;
if (this._tryToRun) {
return;
}
this._tryToRun = true;
this._resumeAudioContext().then(function() {
_this._tryToRun = false;
if (_this._muteButton) {
_this._hideMuteButton();
}
}).catch(function() {
_this._tryToRun = false;
_this.unlocked = false;
});
this.unlocked = true;
this.onAudioUnlockedObservable.notifyObservers(this);
};
AudioEngine2.prototype._triggerSuspendedState = function() {
this.unlocked = false;
this.onAudioLockedObservable.notifyObservers(this);
this._displayMuteButton();
};
AudioEngine2.prototype._displayMuteButton = function() {
var _this = this;
if (this.useCustomUnlockedButton) {
return;
}
this._muteButton = document.createElement("BUTTON");
this._muteButton.className = "babylonUnmuteIcon";
this._muteButton.id = "babylonUnmuteIconBtn";
this._muteButton.title = "Unmute";
var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
var style = document.createElement("style");
style.appendChild(document.createTextNode(css));
document.getElementsByTagName("head")[0].appendChild(style);
document.body.appendChild(this._muteButton);
this._moveButtonToTopLeft();
this._muteButton.addEventListener("touchend", function() {
_this._triggerRunningState();
}, true);
this._muteButton.addEventListener("click", function() {
_this._triggerRunningState();
}, true);
window.addEventListener("resize", this._onResize);
};
AudioEngine2.prototype._moveButtonToTopLeft = function() {
if (this._hostElement && this._muteButton) {
this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
}
};
AudioEngine2.prototype._hideMuteButton = function() {
if (this._muteButton) {
document.body.removeChild(this._muteButton);
this._muteButton = null;
}
};
AudioEngine2.prototype.dispose = function() {
if (this.canUseWebAudio && this._audioContextInitialized) {
if (this._connectedAnalyser && this._audioContext) {
this._connectedAnalyser.stopDebugCanvas();
this._connectedAnalyser.dispose();
this.masterGain.disconnect();
this.masterGain.connect(this._audioContext.destination);
this._connectedAnalyser = null;
}
this.masterGain.gain.value = 1;
}
this.WarnedWebAudioUnsupported = false;
this._hideMuteButton();
window.removeEventListener("resize", this._onResize);
this.onAudioUnlockedObservable.clear();
this.onAudioLockedObservable.clear();
};
AudioEngine2.prototype.getGlobalVolume = function() {
if (this.canUseWebAudio && this._audioContextInitialized) {
return this.masterGain.gain.value;
} else {
return -1;
}
};
AudioEngine2.prototype.setGlobalVolume = function(newVolume) {
if (this.canUseWebAudio && this._audioContextInitialized) {
this.masterGain.gain.value = newVolume;
}
};
AudioEngine2.prototype.connectToAnalyser = function(analyser) {
if (this._connectedAnalyser) {
this._connectedAnalyser.stopDebugCanvas();
}
if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
this._connectedAnalyser = analyser;
this.masterGain.disconnect();
this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
}
};
return AudioEngine2;
}()
);
BABYLON2.AudioEngine = AudioEngine;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Sound = (
/** @class */
function() {
function Sound2(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
if (readyToPlayCallback === void 0) {
readyToPlayCallback = null;
}
var _this = this;
this.autoplay = false;
this.loop = false;
this.useCustomAttenuation = false;
this.isPlaying = false;
this.isPaused = false;
this.spatialSound = false;
this.refDistance = 1;
this.rolloffFactor = 1;
this.maxDistance = 100;
this.distanceModel = "linear";
this.onEndedObservable = new BABYLON2.Observable();
this._panningModel = "equalpower";
this._playbackRate = 1;
this._streaming = false;
this._startTime = 0;
this._startOffset = 0;
this._position = BABYLON2.Vector3.Zero();
this._positionInEmitterSpace = false;
this._localDirection = new BABYLON2.Vector3(1, 0, 0);
this._volume = 1;
this._isReadyToPlay = false;
this._isDirectional = false;
this._coneInnerAngle = 360;
this._coneOuterAngle = 360;
this._coneOuterGain = 0;
this._isOutputConnected = false;
this._urlType = "Unknown";
this.name = name;
this._scene = scene;
var compo = scene._getComponent(BABYLON2.SceneComponentConstants.NAME_AUDIO);
if (!compo) {
compo = new BABYLON2.AudioSceneComponent(scene);
scene._addComponent(compo);
}
this._readyToPlayCallback = readyToPlayCallback;
this._customAttenuationFunction = function(currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
if (currentDistance < maxDistance) {
return currentVolume * (1 - currentDistance / maxDistance);
} else {
return 0;
}
};
if (options) {
this.autoplay = options.autoplay || false;
this.loop = options.loop || false;
if (options.volume !== void 0) {
this._volume = options.volume;
}
this.spatialSound = options.spatialSound || false;
this.maxDistance = options.maxDistance || 100;
this.useCustomAttenuation = options.useCustomAttenuation || false;
this.rolloffFactor = options.rolloffFactor || 1;
this.refDistance = options.refDistance || 1;
this.distanceModel = options.distanceModel || "linear";
this._playbackRate = options.playbackRate || 1;
this._streaming = options.streaming || false;
}
if (BABYLON2.Engine.audioEngine.canUseWebAudio && BABYLON2.Engine.audioEngine.audioContext) {
this._soundGain = BABYLON2.Engine.audioEngine.audioContext.createGain();
this._soundGain.gain.value = this._volume;
this._inputAudioNode = this._soundGain;
this._outputAudioNode = this._soundGain;
if (this.spatialSound) {
this._createSpatialParameters();
}
this._scene.mainSoundTrack.AddSound(this);
var validParameter = true;
if (urlOrArrayBuffer) {
try {
if (typeof urlOrArrayBuffer === "string") {
this._urlType = "String";
} else if (urlOrArrayBuffer instanceof ArrayBuffer) {
this._urlType = "ArrayBuffer";
} else if (urlOrArrayBuffer instanceof MediaStream) {
this._urlType = "MediaStream";
} else if (Array.isArray(urlOrArrayBuffer)) {
this._urlType = "Array";
}
var urls = [];
var codecSupportedFound = false;
switch (this._urlType) {
case "MediaStream":
this._streaming = true;
this._isReadyToPlay = true;
this._streamingSource = BABYLON2.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
if (this.autoplay) {
this.play();
}
if (this._readyToPlayCallback) {
this._readyToPlayCallback();
}
break;
case "ArrayBuffer":
if (urlOrArrayBuffer.byteLength > 0) {
codecSupportedFound = true;
this._soundLoaded(urlOrArrayBuffer);
}
break;
case "String":
urls.push(urlOrArrayBuffer);
case "Array":
if (urls.length === 0) {
urls = urlOrArrayBuffer;
}
for (var i2 = 0; i2 < urls.length; i2++) {
var url = urls[i2];
if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON2.Engine.audioEngine.isMP3supported) {
codecSupportedFound = true;
}
if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON2.Engine.audioEngine.isOGGsupported) {
codecSupportedFound = true;
}
if (url.indexOf(".wav", url.length - 4) !== -1) {
codecSupportedFound = true;
}
if (url.indexOf("blob:") !== -1) {
codecSupportedFound = true;
}
if (codecSupportedFound) {
if (!this._streaming) {
this._scene._loadFile(url, function(data2) {
_this._soundLoaded(data2);
}, void 0, true, true, function(exception) {
if (exception) {
BABYLON2.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
}
BABYLON2.Tools.Error("Sound creation aborted.");
_this._scene.mainSoundTrack.RemoveSound(_this);
});
} else {
this._htmlAudioElement = new Audio(url);
this._htmlAudioElement.controls = false;
this._htmlAudioElement.loop = this.loop;
BABYLON2.Tools.SetCorsBehavior(url, this._htmlAudioElement);
this._htmlAudioElement.preload = "auto";
this._htmlAudioElement.addEventListener("canplaythrough", function() {
_this._isReadyToPlay = true;
if (_this.autoplay) {
_this.play();
}
if (_this._readyToPlayCallback) {
_this._readyToPlayCallback();
}
});
document.body.appendChild(this._htmlAudioElement);
this._htmlAudioElement.load();
}
break;
}
}
break;
default:
validParameter = false;
break;
}
if (!validParameter) {
BABYLON2.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
} else {
if (!codecSupportedFound) {
this._isReadyToPlay = true;
if (this._readyToPlayCallback) {
window.setTimeout(function() {
if (_this._readyToPlayCallback) {
_this._readyToPlayCallback();
}
}, 1e3);
}
}
}
} catch (ex) {
BABYLON2.Tools.Error("Unexpected error. Sound creation aborted.");
this._scene.mainSoundTrack.RemoveSound(this);
}
}
} else {
this._scene.mainSoundTrack.AddSound(this);
if (!BABYLON2.Engine.audioEngine.WarnedWebAudioUnsupported) {
BABYLON2.Tools.Error("Web Audio is not supported by your browser.");
BABYLON2.Engine.audioEngine.WarnedWebAudioUnsupported = true;
}
if (this._readyToPlayCallback) {
window.setTimeout(function() {
if (_this._readyToPlayCallback) {
_this._readyToPlayCallback();
}
}, 1e3);
}
}
}
Sound2.prototype.dispose = function() {
if (BABYLON2.Engine.audioEngine.canUseWebAudio) {
if (this.isPlaying) {
this.stop();
}
this._isReadyToPlay = false;
if (this.soundTrackId === -1) {
this._scene.mainSoundTrack.RemoveSound(this);
} else if (this._scene.soundTracks) {
this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
}
if (this._soundGain) {
this._soundGain.disconnect();
this._soundGain = null;
}
if (this._soundPanner) {
this._soundPanner.disconnect();
this._soundPanner = null;
}
if (this._soundSource) {
this._soundSource.disconnect();
this._soundSource = null;
}
this._audioBuffer = null;
if (this._htmlAudioElement) {
this._htmlAudioElement.pause();
this._htmlAudioElement.src = "";
document.body.removeChild(this._htmlAudioElement);
}
if (this._streamingSource) {
this._streamingSource.disconnect();
}
if (this._connectedMesh && this._registerFunc) {
this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
this._connectedMesh = null;
}
}
};
Sound2.prototype.isReady = function() {
return this._isReadyToPlay;
};
Sound2.prototype._soundLoaded = function(audioData) {
var _this = this;
if (!BABYLON2.Engine.audioEngine.audioContext) {
return;
}
BABYLON2.Engine.audioEngine.audioContext.decodeAudioData(audioData, function(buffer) {
_this._audioBuffer = buffer;
_this._isReadyToPlay = true;
if (_this.autoplay) {
_this.play();
}
if (_this._readyToPlayCallback) {
_this._readyToPlayCallback();
}
}, function(err) {
BABYLON2.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err);
});
};
Sound2.prototype.setAudioBuffer = function(audioBuffer) {
if (BABYLON2.Engine.audioEngine.canUseWebAudio) {
this._audioBuffer = audioBuffer;
this._isReadyToPlay = true;
}
};
Sound2.prototype.updateOptions = function(options) {
if (options) {
this.loop = options.loop || this.loop;
this.maxDistance = options.maxDistance || this.maxDistance;
this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
this.refDistance = options.refDistance || this.refDistance;
this.distanceModel = options.distanceModel || this.distanceModel;
this._playbackRate = options.playbackRate || this._playbackRate;
this._updateSpatialParameters();
if (this.isPlaying) {
if (this._streaming && this._htmlAudioElement) {
this._htmlAudioElement.playbackRate = this._playbackRate;
} else {
if (this._soundSource) {
this._soundSource.playbackRate.value = this._playbackRate;
}
}
}
}
};
Sound2.prototype._createSpatialParameters = function() {
if (BABYLON2.Engine.audioEngine.canUseWebAudio && BABYLON2.Engine.audioEngine.audioContext) {
if (this._scene.headphone) {
this._panningModel = "HRTF";
}
this._soundPanner = BABYLON2.Engine.audioEngine.audioContext.createPanner();
this._updateSpatialParameters();
this._soundPanner.connect(this._outputAudioNode);
this._inputAudioNode = this._soundPanner;
}
};
Sound2.prototype._updateSpatialParameters = function() {
if (this.spatialSound && this._soundPanner) {
if (this.useCustomAttenuation) {
this._soundPanner.distanceModel = "linear";
this._soundPanner.maxDistance = Number.MAX_VALUE;
this._soundPanner.refDistance = 1;
this._soundPanner.rolloffFactor = 1;
this._soundPanner.panningModel = this._panningModel;
} else {
this._soundPanner.distanceModel = this.distanceModel;
this._soundPanner.maxDistance = this.maxDistance;
this._soundPanner.refDistance = this.refDistance;
this._soundPanner.rolloffFactor = this.rolloffFactor;
this._soundPanner.panningModel = this._panningModel;
}
}
};
Sound2.prototype.switchPanningModelToHRTF = function() {
this._panningModel = "HRTF";
this._switchPanningModel();
};
Sound2.prototype.switchPanningModelToEqualPower = function() {
this._panningModel = "equalpower";
this._switchPanningModel();
};
Sound2.prototype._switchPanningModel = function() {
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
this._soundPanner.panningModel = this._panningModel;
}
};
Sound2.prototype.connectToSoundTrackAudioNode = function(soundTrackAudioNode) {
if (BABYLON2.Engine.audioEngine.canUseWebAudio) {
if (this._isOutputConnected) {
this._outputAudioNode.disconnect();
}
this._outputAudioNode.connect(soundTrackAudioNode);
this._isOutputConnected = true;
}
};
Sound2.prototype.setDirectionalCone = function(coneInnerAngle, coneOuterAngle, coneOuterGain) {
if (coneOuterAngle < coneInnerAngle) {
BABYLON2.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
return;
}
this._coneInnerAngle = coneInnerAngle;
this._coneOuterAngle = coneOuterAngle;
this._coneOuterGain = coneOuterGain;
this._isDirectional = true;
if (this.isPlaying && this.loop) {
this.stop();
this.play();
}
};
Object.defineProperty(Sound2.prototype, "directionalConeInnerAngle", {
/**
* Gets or sets the inner angle for the directional cone.
*/
get: function() {
return this._coneInnerAngle;
},
/**
* Gets or sets the inner angle for the directional cone.
*/
set: function(value) {
if (value != this._coneInnerAngle) {
if (this._coneOuterAngle < value) {
BABYLON2.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
return;
}
this._coneInnerAngle = value;
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
this._soundPanner.coneInnerAngle = this._coneInnerAngle;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Sound2.prototype, "directionalConeOuterAngle", {
/**
* Gets or sets the outer angle for the directional cone.
*/
get: function() {
return this._coneOuterAngle;
},
/**
* Gets or sets the outer angle for the directional cone.
*/
set: function(value) {
if (value != this._coneOuterAngle) {
if (value < this._coneInnerAngle) {
BABYLON2.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
return;
}
this._coneOuterAngle = value;
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
this._soundPanner.coneOuterAngle = this._coneOuterAngle;
}
}
},
enumerable: true,
configurable: true
});
Sound2.prototype.setPosition = function(newPosition) {
this._position = newPosition;
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
}
};
Sound2.prototype.setLocalDirectionToMesh = function(newLocalDirection) {
this._localDirection = newLocalDirection;
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
this._updateDirection();
}
};
Sound2.prototype._updateDirection = function() {
if (!this._connectedMesh || !this._soundPanner) {
return;
}
var mat = this._connectedMesh.getWorldMatrix();
var direction = BABYLON2.Vector3.TransformNormal(this._localDirection, mat);
direction.normalize();
this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
};
Sound2.prototype.updateDistanceFromListener = function() {
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
}
};
Sound2.prototype.setAttenuationFunction = function(callback) {
this._customAttenuationFunction = callback;
};
Sound2.prototype.play = function(time, offset) {
var _this = this;
if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON2.Engine.audioEngine.audioContext) {
try {
if (this._startOffset < 0) {
time = -this._startOffset;
this._startOffset = 0;
}
var startTime = time ? BABYLON2.Engine.audioEngine.audioContext.currentTime + time : BABYLON2.Engine.audioEngine.audioContext.currentTime;
if (!this._soundSource || !this._streamingSource) {
if (this.spatialSound && this._soundPanner) {
if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
}
if (this._isDirectional) {
this._soundPanner.coneInnerAngle = this._coneInnerAngle;
this._soundPanner.coneOuterAngle = this._coneOuterAngle;
this._soundPanner.coneOuterGain = this._coneOuterGain;
if (this._connectedMesh) {
this._updateDirection();
} else {
this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
}
}
}
}
if (this._streaming) {
if (!this._streamingSource) {
this._streamingSource = BABYLON2.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
this._htmlAudioElement.onended = function() {
_this._onended();
};
this._htmlAudioElement.playbackRate = this._playbackRate;
}
this._streamingSource.disconnect();
this._streamingSource.connect(this._inputAudioNode);
if (this._htmlAudioElement) {
var tryToPlay = function() {
if (BABYLON2.Engine.audioEngine.unlocked) {
var playPromise = _this._htmlAudioElement.play();
if (playPromise !== void 0) {
playPromise.catch(function(error) {
BABYLON2.Engine.audioEngine.lock();
BABYLON2.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function() {
tryToPlay();
});
});
}
} else {
BABYLON2.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function() {
tryToPlay();
});
}
};
tryToPlay();
}
} else {
this._soundSource = BABYLON2.Engine.audioEngine.audioContext.createBufferSource();
this._soundSource.buffer = this._audioBuffer;
this._soundSource.connect(this._inputAudioNode);
this._soundSource.loop = this.loop;
this._soundSource.playbackRate.value = this._playbackRate;
this._soundSource.onended = function() {
_this._onended();
};
if (this._soundSource.buffer) {
this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
}
}
this._startTime = startTime;
this.isPlaying = true;
this.isPaused = false;
} catch (ex) {
BABYLON2.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
}
}
};
Sound2.prototype._onended = function() {
this.isPlaying = false;
if (this.onended) {
this.onended();
}
this.onEndedObservable.notifyObservers(this);
};
Sound2.prototype.stop = function(time) {
if (this.isPlaying) {
if (this._streaming) {
if (this._htmlAudioElement) {
this._htmlAudioElement.pause();
if (this._htmlAudioElement.currentTime > 0) {
this._htmlAudioElement.currentTime = 0;
}
} else {
this._streamingSource.disconnect();
}
} else if (BABYLON2.Engine.audioEngine.audioContext && this._soundSource) {
var stopTime = time ? BABYLON2.Engine.audioEngine.audioContext.currentTime + time : BABYLON2.Engine.audioEngine.audioContext.currentTime;
this._soundSource.stop(stopTime);
this._soundSource.onended = function() {
};
if (!this.isPaused) {
this._startOffset = 0;
}
}
this.isPlaying = false;
}
};
Sound2.prototype.pause = function() {
if (this.isPlaying) {
this.isPaused = true;
if (this._streaming) {
if (this._htmlAudioElement) {
this._htmlAudioElement.pause();
} else {
this._streamingSource.disconnect();
}
} else if (BABYLON2.Engine.audioEngine.audioContext) {
this.stop(0);
this._startOffset += BABYLON2.Engine.audioEngine.audioContext.currentTime - this._startTime;
}
}
};
Sound2.prototype.setVolume = function(newVolume, time) {
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this._soundGain) {
if (time && BABYLON2.Engine.audioEngine.audioContext) {
this._soundGain.gain.cancelScheduledValues(BABYLON2.Engine.audioEngine.audioContext.currentTime);
this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON2.Engine.audioEngine.audioContext.currentTime);
this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON2.Engine.audioEngine.audioContext.currentTime + time);
} else {
this._soundGain.gain.value = newVolume;
}
}
this._volume = newVolume;
};
Sound2.prototype.setPlaybackRate = function(newPlaybackRate) {
this._playbackRate = newPlaybackRate;
if (this.isPlaying) {
if (this._streaming && this._htmlAudioElement) {
this._htmlAudioElement.playbackRate = this._playbackRate;
} else if (this._soundSource) {
this._soundSource.playbackRate.value = this._playbackRate;
}
}
};
Sound2.prototype.getVolume = function() {
return this._volume;
};
Sound2.prototype.attachToMesh = function(meshToConnectTo) {
var _this = this;
if (this._connectedMesh && this._registerFunc) {
this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
this._registerFunc = null;
}
this._connectedMesh = meshToConnectTo;
if (!this.spatialSound) {
this.spatialSound = true;
this._createSpatialParameters();
if (this.isPlaying && this.loop) {
this.stop();
this.play();
}
}
this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
this._registerFunc = function(connectedMesh) {
return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
};
meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
};
Sound2.prototype.detachFromMesh = function() {
if (this._connectedMesh && this._registerFunc) {
this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
this._registerFunc = null;
this._connectedMesh = null;
}
};
Sound2.prototype._onRegisterAfterWorldMatrixUpdate = function(node) {
if (!node.getBoundingInfo) {
return;
}
var mesh2 = node;
if (this._positionInEmitterSpace) {
mesh2.worldMatrixFromCache.invertToRef(BABYLON2.Tmp.Matrix[0]);
this.setPosition(BABYLON2.Tmp.Matrix[0].getTranslation());
} else {
var boundingInfo = mesh2.getBoundingInfo();
this.setPosition(boundingInfo.boundingSphere.centerWorld);
}
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
this._updateDirection();
}
};
Sound2.prototype.clone = function() {
var _this = this;
if (!this._streaming) {
var setBufferAndRun = function() {
if (_this._isReadyToPlay) {
clonedSound._audioBuffer = _this.getAudioBuffer();
clonedSound._isReadyToPlay = true;
if (clonedSound.autoplay) {
clonedSound.play();
}
} else {
window.setTimeout(setBufferAndRun, 300);
}
};
var currentOptions = {
autoplay: this.autoplay,
loop: this.loop,
volume: this._volume,
spatialSound: this.spatialSound,
maxDistance: this.maxDistance,
useCustomAttenuation: this.useCustomAttenuation,
rolloffFactor: this.rolloffFactor,
refDistance: this.refDistance,
distanceModel: this.distanceModel
};
var clonedSound = new Sound2(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
if (this.useCustomAttenuation) {
clonedSound.setAttenuationFunction(this._customAttenuationFunction);
}
clonedSound.setPosition(this._position);
clonedSound.setPlaybackRate(this._playbackRate);
setBufferAndRun();
return clonedSound;
} else {
return null;
}
};
Sound2.prototype.getAudioBuffer = function() {
return this._audioBuffer;
};
Sound2.prototype.serialize = function() {
var serializationObject = {
name: this.name,
url: this.name,
autoplay: this.autoplay,
loop: this.loop,
volume: this._volume,
spatialSound: this.spatialSound,
maxDistance: this.maxDistance,
rolloffFactor: this.rolloffFactor,
refDistance: this.refDistance,
distanceModel: this.distanceModel,
playbackRate: this._playbackRate,
panningModel: this._panningModel,
soundTrackId: this.soundTrackId
};
if (this.spatialSound) {
if (this._connectedMesh) {
serializationObject.connectedMeshId = this._connectedMesh.id;
}
serializationObject.position = this._position.asArray();
serializationObject.refDistance = this.refDistance;
serializationObject.distanceModel = this.distanceModel;
serializationObject.isDirectional = this._isDirectional;
serializationObject.localDirectionToMesh = this._localDirection.asArray();
serializationObject.coneInnerAngle = this._coneInnerAngle;
serializationObject.coneOuterAngle = this._coneOuterAngle;
serializationObject.coneOuterGain = this._coneOuterGain;
}
return serializationObject;
};
Sound2.Parse = function(parsedSound, scene, rootUrl, sourceSound) {
var soundName = parsedSound.name;
var soundUrl;
if (parsedSound.url) {
soundUrl = rootUrl + parsedSound.url;
} else {
soundUrl = rootUrl + soundName;
}
var options = {
autoplay: parsedSound.autoplay,
loop: parsedSound.loop,
volume: parsedSound.volume,
spatialSound: parsedSound.spatialSound,
maxDistance: parsedSound.maxDistance,
rolloffFactor: parsedSound.rolloffFactor,
refDistance: parsedSound.refDistance,
distanceModel: parsedSound.distanceModel,
playbackRate: parsedSound.playbackRate
};
var newSound;
if (!sourceSound) {
newSound = new Sound2(soundName, soundUrl, scene, function() {
scene._removePendingData(newSound);
}, options);
scene._addPendingData(newSound);
} else {
var setBufferAndRun = function() {
if (sourceSound._isReadyToPlay) {
newSound._audioBuffer = sourceSound.getAudioBuffer();
newSound._isReadyToPlay = true;
if (newSound.autoplay) {
newSound.play();
}
} else {
window.setTimeout(setBufferAndRun, 300);
}
};
newSound = new Sound2(soundName, new ArrayBuffer(0), scene, null, options);
setBufferAndRun();
}
if (parsedSound.position) {
var soundPosition = BABYLON2.Vector3.FromArray(parsedSound.position);
newSound.setPosition(soundPosition);
}
if (parsedSound.isDirectional) {
newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
if (parsedSound.localDirectionToMesh) {
var localDirectionToMesh = BABYLON2.Vector3.FromArray(parsedSound.localDirectionToMesh);
newSound.setLocalDirectionToMesh(localDirectionToMesh);
}
}
if (parsedSound.connectedMeshId) {
var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
if (connectedMesh) {
newSound.attachToMesh(connectedMesh);
}
}
return newSound;
};
return Sound2;
}()
);
BABYLON2.Sound = Sound;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SoundTrack = (
/** @class */
function() {
function SoundTrack2(scene, options) {
if (options === void 0) {
options = {};
}
this.id = -1;
this._isMainTrack = false;
this._isInitialized = false;
this._scene = scene;
this.soundCollection = new Array();
this._options = options;
if (!this._isMainTrack && this._scene.soundTracks) {
this._scene.soundTracks.push(this);
this.id = this._scene.soundTracks.length - 1;
}
}
SoundTrack2.prototype._initializeSoundTrackAudioGraph = function() {
if (BABYLON2.Engine.audioEngine.canUseWebAudio && BABYLON2.Engine.audioEngine.audioContext) {
this._outputAudioNode = BABYLON2.Engine.audioEngine.audioContext.createGain();
this._outputAudioNode.connect(BABYLON2.Engine.audioEngine.masterGain);
if (this._options) {
if (this._options.volume) {
this._outputAudioNode.gain.value = this._options.volume;
}
if (this._options.mainTrack) {
this._isMainTrack = this._options.mainTrack;
}
}
this._isInitialized = true;
}
};
SoundTrack2.prototype.dispose = function() {
if (BABYLON2.Engine.audioEngine && BABYLON2.Engine.audioEngine.canUseWebAudio) {
if (this._connectedAnalyser) {
this._connectedAnalyser.stopDebugCanvas();
}
while (this.soundCollection.length) {
this.soundCollection[0].dispose();
}
if (this._outputAudioNode) {
this._outputAudioNode.disconnect();
}
this._outputAudioNode = null;
}
};
SoundTrack2.prototype.AddSound = function(sound) {
if (!this._isInitialized) {
this._initializeSoundTrackAudioGraph();
}
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
sound.connectToSoundTrackAudioNode(this._outputAudioNode);
}
if (sound.soundTrackId) {
if (sound.soundTrackId === -1) {
this._scene.mainSoundTrack.RemoveSound(sound);
} else if (this._scene.soundTracks) {
this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
}
}
this.soundCollection.push(sound);
sound.soundTrackId = this.id;
};
SoundTrack2.prototype.RemoveSound = function(sound) {
var index = this.soundCollection.indexOf(sound);
if (index !== -1) {
this.soundCollection.splice(index, 1);
}
};
SoundTrack2.prototype.setVolume = function(newVolume) {
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
this._outputAudioNode.gain.value = newVolume;
}
};
SoundTrack2.prototype.switchPanningModelToHRTF = function() {
if (BABYLON2.Engine.audioEngine.canUseWebAudio) {
for (var i2 = 0; i2 < this.soundCollection.length; i2++) {
this.soundCollection[i2].switchPanningModelToHRTF();
}
}
};
SoundTrack2.prototype.switchPanningModelToEqualPower = function() {
if (BABYLON2.Engine.audioEngine.canUseWebAudio) {
for (var i2 = 0; i2 < this.soundCollection.length; i2++) {
this.soundCollection[i2].switchPanningModelToEqualPower();
}
}
};
SoundTrack2.prototype.connectToAnalyser = function(analyser) {
if (this._connectedAnalyser) {
this._connectedAnalyser.stopDebugCanvas();
}
this._connectedAnalyser = analyser;
if (BABYLON2.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
this._outputAudioNode.disconnect();
this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON2.Engine.audioEngine.masterGain);
}
};
return SoundTrack2;
}()
);
BABYLON2.SoundTrack = SoundTrack;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Analyser = (
/** @class */
function() {
function Analyser2(scene) {
this.SMOOTHING = 0.75;
this.FFT_SIZE = 512;
this.BARGRAPHAMPLITUDE = 256;
this.DEBUGCANVASPOS = { x: 20, y: 20 };
this.DEBUGCANVASSIZE = { width: 320, height: 200 };
this._scene = scene;
this._audioEngine = BABYLON2.Engine.audioEngine;
if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
this._webAudioAnalyser.minDecibels = -140;
this._webAudioAnalyser.maxDecibels = 0;
this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
}
}
Analyser2.prototype.getFrequencyBinCount = function() {
if (this._audioEngine.canUseWebAudio) {
return this._webAudioAnalyser.frequencyBinCount;
} else {
return 0;
}
};
Analyser2.prototype.getByteFrequencyData = function() {
if (this._audioEngine.canUseWebAudio) {
this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
this._webAudioAnalyser.fftSize = this.FFT_SIZE;
this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
}
return this._byteFreqs;
};
Analyser2.prototype.getByteTimeDomainData = function() {
if (this._audioEngine.canUseWebAudio) {
this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
this._webAudioAnalyser.fftSize = this.FFT_SIZE;
this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
}
return this._byteTime;
};
Analyser2.prototype.getFloatFrequencyData = function() {
if (this._audioEngine.canUseWebAudio) {
this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
this._webAudioAnalyser.fftSize = this.FFT_SIZE;
this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
}
return this._floatFreqs;
};
Analyser2.prototype.drawDebugCanvas = function() {
var _this = this;
if (this._audioEngine.canUseWebAudio) {
if (!this._debugCanvas) {
this._debugCanvas = document.createElement("canvas");
this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
this._debugCanvas.style.position = "absolute";
this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
this._debugCanvasContext = this._debugCanvas.getContext("2d");
document.body.appendChild(this._debugCanvas);
this._registerFunc = function() {
_this.drawDebugCanvas();
};
this._scene.registerBeforeRender(this._registerFunc);
}
if (this._registerFunc && this._debugCanvasContext) {
var workingArray = this.getByteFrequencyData();
this._debugCanvasContext.fillStyle = "rgb(0, 0, 0)";
this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
for (var i2 = 0; i2 < this.getFrequencyBinCount(); i2++) {
var value = workingArray[i2];
var percent = value / this.BARGRAPHAMPLITUDE;
var height = this.DEBUGCANVASSIZE.height * percent;
var offset = this.DEBUGCANVASSIZE.height - height - 1;
var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
var hue = i2 / this.getFrequencyBinCount() * 360;
this._debugCanvasContext.fillStyle = "hsl(" + hue + ", 100%, 50%)";
this._debugCanvasContext.fillRect(i2 * barWidth, offset, barWidth, height);
}
}
}
};
Analyser2.prototype.stopDebugCanvas = function() {
if (this._debugCanvas) {
if (this._registerFunc) {
this._scene.unregisterBeforeRender(this._registerFunc);
this._registerFunc = null;
}
document.body.removeChild(this._debugCanvas);
this._debugCanvas = null;
this._debugCanvasContext = null;
}
};
Analyser2.prototype.connectAudioNodes = function(inputAudioNode, outputAudioNode) {
if (this._audioEngine.canUseWebAudio) {
inputAudioNode.connect(this._webAudioAnalyser);
this._webAudioAnalyser.connect(outputAudioNode);
}
};
Analyser2.prototype.dispose = function() {
if (this._audioEngine.canUseWebAudio) {
this._webAudioAnalyser.disconnect();
}
};
return Analyser2;
}()
);
BABYLON2.Analyser = Analyser;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var WeightedSound = (
/** @class */
function() {
function WeightedSound2(loop, sounds, weights) {
var _this = this;
this.loop = false;
this._coneInnerAngle = 360;
this._coneOuterAngle = 360;
this._volume = 1;
this.isPlaying = false;
this.isPaused = false;
this._sounds = [];
this._weights = [];
if (sounds.length !== weights.length) {
throw new Error("Sounds length does not equal weights length");
}
this.loop = loop;
this._weights = weights;
var weightSum = 0;
for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
var weight = weights_1[_i];
weightSum += weight;
}
var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
for (var i2 = 0; i2 < this._weights.length; i2++) {
this._weights[i2] *= invWeightSum;
}
this._sounds = sounds;
for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
var sound = _b[_a];
sound.onEndedObservable.add(function() {
_this._onended();
});
}
}
Object.defineProperty(WeightedSound2.prototype, "directionalConeInnerAngle", {
/**
* The size of cone in degrees for a directional sound in which there will be no attenuation.
*/
get: function() {
return this._coneInnerAngle;
},
/**
* The size of cone in degress for a directional sound in which there will be no attenuation.
*/
set: function(value) {
if (value !== this._coneInnerAngle) {
if (this._coneOuterAngle < value) {
BABYLON2.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
return;
}
this._coneInnerAngle = value;
for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
var sound = _a[_i];
sound.directionalConeInnerAngle = value;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(WeightedSound2.prototype, "directionalConeOuterAngle", {
/**
* Size of cone in degrees for a directional sound outside of which there will be no sound.
* Listener angles between innerAngle and outerAngle will falloff linearly.
*/
get: function() {
return this._coneOuterAngle;
},
/**
* Size of cone in degrees for a directional sound outside of which there will be no sound.
* Listener angles between innerAngle and outerAngle will falloff linearly.
*/
set: function(value) {
if (value !== this._coneOuterAngle) {
if (value < this._coneInnerAngle) {
BABYLON2.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
return;
}
this._coneOuterAngle = value;
for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
var sound = _a[_i];
sound.directionalConeOuterAngle = value;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(WeightedSound2.prototype, "volume", {
/**
* Playback volume.
*/
get: function() {
return this._volume;
},
/**
* Playback volume.
*/
set: function(value) {
if (value !== this._volume) {
for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
var sound = _a[_i];
sound.setVolume(value);
}
}
},
enumerable: true,
configurable: true
});
WeightedSound2.prototype._onended = function() {
if (this._currentIndex !== void 0) {
this._sounds[this._currentIndex].autoplay = false;
}
if (this.loop && this.isPlaying) {
this.play();
} else {
this.isPlaying = false;
}
};
WeightedSound2.prototype.pause = function() {
this.isPaused = true;
if (this._currentIndex !== void 0) {
this._sounds[this._currentIndex].pause();
}
};
WeightedSound2.prototype.stop = function() {
this.isPlaying = false;
if (this._currentIndex !== void 0) {
this._sounds[this._currentIndex].stop();
}
};
WeightedSound2.prototype.play = function(startOffset) {
if (!this.isPaused) {
this.stop();
var randomValue = Math.random();
var total = 0;
for (var i2 = 0; i2 < this._weights.length; i2++) {
total += this._weights[i2];
if (randomValue <= total) {
this._currentIndex = i2;
break;
}
}
}
var sound = this._sounds[this._currentIndex];
if (sound.isReady()) {
sound.play(0, this.isPaused ? void 0 : startOffset);
} else {
sound.autoplay = true;
}
this.isPlaying = true;
this.isPaused = false;
};
return WeightedSound2;
}()
);
BABYLON2.WeightedSound = WeightedSound;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractScene.AddParser(BABYLON2.SceneComponentConstants.NAME_AUDIO, function(parsedData, scene, container, rootUrl) {
var loadedSounds = [];
var loadedSound;
container.sounds = container.sounds || [];
if (parsedData.sounds !== void 0 && parsedData.sounds !== null) {
for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
var parsedSound = parsedData.sounds[index];
if (BABYLON2.Engine.audioEngine.canUseWebAudio) {
if (!parsedSound.url) {
parsedSound.url = parsedSound.name;
}
if (!loadedSounds[parsedSound.url]) {
loadedSound = BABYLON2.Sound.Parse(parsedSound, scene, rootUrl);
loadedSounds[parsedSound.url] = loadedSound;
container.sounds.push(loadedSound);
} else {
container.sounds.push(BABYLON2.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
}
} else {
container.sounds.push(new BABYLON2.Sound(parsedSound.name, null, scene));
}
}
}
loadedSounds = [];
});
Object.defineProperty(BABYLON2.Scene.prototype, "mainSoundTrack", {
get: function() {
var compo = this._getComponent(BABYLON2.SceneComponentConstants.NAME_AUDIO);
if (!compo) {
compo = new AudioSceneComponent(this);
this._addComponent(compo);
}
if (!this._mainSoundTrack) {
this._mainSoundTrack = new BABYLON2.SoundTrack(this, { mainTrack: true });
}
return this._mainSoundTrack;
},
enumerable: true,
configurable: true
});
BABYLON2.Scene.prototype.getSoundByName = function(name) {
var index;
for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
if (this.mainSoundTrack.soundCollection[index].name === name) {
return this.mainSoundTrack.soundCollection[index];
}
}
if (this.soundTracks) {
for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
return this.soundTracks[sdIndex].soundCollection[index];
}
}
}
}
return null;
};
Object.defineProperty(BABYLON2.Scene.prototype, "audioEnabled", {
get: function() {
var compo = this._getComponent(BABYLON2.SceneComponentConstants.NAME_AUDIO);
if (!compo) {
compo = new AudioSceneComponent(this);
this._addComponent(compo);
}
return compo.audioEnabled;
},
set: function(value) {
var compo = this._getComponent(BABYLON2.SceneComponentConstants.NAME_AUDIO);
if (!compo) {
compo = new AudioSceneComponent(this);
this._addComponent(compo);
}
if (value) {
compo.enableAudio();
} else {
compo.disableAudio();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BABYLON2.Scene.prototype, "headphone", {
get: function() {
var compo = this._getComponent(BABYLON2.SceneComponentConstants.NAME_AUDIO);
if (!compo) {
compo = new AudioSceneComponent(this);
this._addComponent(compo);
}
return compo.headphone;
},
set: function(value) {
var compo = this._getComponent(BABYLON2.SceneComponentConstants.NAME_AUDIO);
if (!compo) {
compo = new AudioSceneComponent(this);
this._addComponent(compo);
}
if (value) {
compo.switchAudioModeForHeadphones();
} else {
compo.switchAudioModeForNormalSpeakers();
}
},
enumerable: true,
configurable: true
});
var AudioSceneComponent = (
/** @class */
function() {
function AudioSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_AUDIO;
this._audioEnabled = true;
this._headphone = false;
this.scene = scene;
scene.soundTracks = new Array();
scene.sounds = new Array();
}
Object.defineProperty(AudioSceneComponent2.prototype, "audioEnabled", {
/**
* Gets whether audio is enabled or not.
* Please use related enable/disable method to switch state.
*/
get: function() {
return this._audioEnabled;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AudioSceneComponent2.prototype, "headphone", {
/**
* Gets whether audio is outputing to headphone or not.
* Please use the according Switch methods to change output.
*/
get: function() {
return this._headphone;
},
enumerable: true,
configurable: true
});
AudioSceneComponent2.prototype.register = function() {
this.scene._afterRenderStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
};
AudioSceneComponent2.prototype.rebuild = function() {
};
AudioSceneComponent2.prototype.serialize = function(serializationObject) {
serializationObject.sounds = [];
if (this.scene.soundTracks) {
for (var index = 0; index < this.scene.soundTracks.length; index++) {
var soundtrack = this.scene.soundTracks[index];
for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
}
}
}
};
AudioSceneComponent2.prototype.addFromContainer = function(container) {
var _this = this;
if (!container.sounds) {
return;
}
container.sounds.forEach(function(sound) {
sound.play();
sound.autoplay = true;
_this.scene.mainSoundTrack.AddSound(sound);
});
};
AudioSceneComponent2.prototype.removeFromContainer = function(container) {
var _this = this;
if (!container.sounds) {
return;
}
container.sounds.forEach(function(sound) {
sound.stop();
sound.autoplay = false;
_this.scene.mainSoundTrack.RemoveSound(sound);
});
};
AudioSceneComponent2.prototype.dispose = function() {
var scene = this.scene;
if (scene._mainSoundTrack) {
scene.mainSoundTrack.dispose();
}
if (scene.soundTracks) {
for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
scene.soundTracks[scIndex].dispose();
}
}
};
AudioSceneComponent2.prototype.disableAudio = function() {
var scene = this.scene;
this._audioEnabled = false;
var i2;
for (i2 = 0; i2 < scene.mainSoundTrack.soundCollection.length; i2++) {
scene.mainSoundTrack.soundCollection[i2].pause();
}
if (scene.soundTracks) {
for (i2 = 0; i2 < scene.soundTracks.length; i2++) {
for (var j = 0; j < scene.soundTracks[i2].soundCollection.length; j++) {
scene.soundTracks[i2].soundCollection[j].pause();
}
}
}
};
AudioSceneComponent2.prototype.enableAudio = function() {
var scene = this.scene;
this._audioEnabled = true;
var i2;
for (i2 = 0; i2 < scene.mainSoundTrack.soundCollection.length; i2++) {
if (scene.mainSoundTrack.soundCollection[i2].isPaused) {
scene.mainSoundTrack.soundCollection[i2].play();
}
}
if (scene.soundTracks) {
for (i2 = 0; i2 < scene.soundTracks.length; i2++) {
for (var j = 0; j < scene.soundTracks[i2].soundCollection.length; j++) {
if (scene.soundTracks[i2].soundCollection[j].isPaused) {
scene.soundTracks[i2].soundCollection[j].play();
}
}
}
}
};
AudioSceneComponent2.prototype.switchAudioModeForHeadphones = function() {
var scene = this.scene;
this._headphone = true;
scene.mainSoundTrack.switchPanningModelToHRTF();
if (scene.soundTracks) {
for (var i2 = 0; i2 < scene.soundTracks.length; i2++) {
scene.soundTracks[i2].switchPanningModelToHRTF();
}
}
};
AudioSceneComponent2.prototype.switchAudioModeForNormalSpeakers = function() {
var scene = this.scene;
this._headphone = false;
scene.mainSoundTrack.switchPanningModelToEqualPower();
if (scene.soundTracks) {
for (var i2 = 0; i2 < scene.soundTracks.length; i2++) {
scene.soundTracks[i2].switchPanningModelToEqualPower();
}
}
};
AudioSceneComponent2.prototype._afterRender = function() {
var scene = this.scene;
if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1) {
return;
}
var listeningCamera;
var audioEngine = BABYLON2.Engine.audioEngine;
if (scene.activeCameras.length > 0) {
listeningCamera = scene.activeCameras[0];
} else {
listeningCamera = scene.activeCamera;
}
if (listeningCamera && audioEngine.audioContext) {
var setDirectly = audioEngine.audioContext.listener.positionX != void 0;
if (setDirectly) {
audioEngine.audioContext.listener.positionX.value = listeningCamera.globalPosition.x;
audioEngine.audioContext.listener.positionY.value = listeningCamera.globalPosition.y;
audioEngine.audioContext.listener.positionZ.value = listeningCamera.globalPosition.z;
} else {
audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z);
}
if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
listeningCamera = listeningCamera.rigCameras[0];
}
var mat = BABYLON2.Matrix.Invert(listeningCamera.getViewMatrix());
var cameraDirection2 = BABYLON2.Vector3.TransformNormal(new BABYLON2.Vector3(0, 0, -1), mat);
cameraDirection2.normalize();
if (!isNaN(cameraDirection2.x) && !isNaN(cameraDirection2.y) && !isNaN(cameraDirection2.z)) {
if (setDirectly) {
audioEngine.audioContext.listener.forwardX.value = cameraDirection2.x;
audioEngine.audioContext.listener.forwardY.value = cameraDirection2.y;
audioEngine.audioContext.listener.forwardZ.value = cameraDirection2.z;
} else {
audioEngine.audioContext.listener.setOrientation(cameraDirection2.x, cameraDirection2.y, cameraDirection2.z, 0, 1, 0);
}
}
var i2;
for (i2 = 0; i2 < scene.mainSoundTrack.soundCollection.length; i2++) {
var sound = scene.mainSoundTrack.soundCollection[i2];
if (sound.useCustomAttenuation) {
sound.updateDistanceFromListener();
}
}
if (scene.soundTracks) {
for (i2 = 0; i2 < scene.soundTracks.length; i2++) {
for (var j = 0; j < scene.soundTracks[i2].soundCollection.length; j++) {
sound = scene.soundTracks[i2].soundCollection[j];
if (sound.useCustomAttenuation) {
sound.updateDistanceFromListener();
}
}
}
}
}
};
return AudioSceneComponent2;
}()
);
BABYLON2.AudioSceneComponent = AudioSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PlaySoundAction = (
/** @class */
function(_super) {
__extends(PlaySoundAction2, _super);
function PlaySoundAction2(triggerOptions, sound, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this._sound = sound;
return _this;
}
PlaySoundAction2.prototype._prepare = function() {
};
PlaySoundAction2.prototype.execute = function() {
if (this._sound !== void 0) {
this._sound.play();
}
};
PlaySoundAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "PlaySoundAction",
properties: [{ name: "sound", value: this._sound.name }]
}, parent);
};
return PlaySoundAction2;
}(BABYLON2.Action)
);
BABYLON2.PlaySoundAction = PlaySoundAction;
var StopSoundAction = (
/** @class */
function(_super) {
__extends(StopSoundAction2, _super);
function StopSoundAction2(triggerOptions, sound, condition) {
var _this = _super.call(this, triggerOptions, condition) || this;
_this._sound = sound;
return _this;
}
StopSoundAction2.prototype._prepare = function() {
};
StopSoundAction2.prototype.execute = function() {
if (this._sound !== void 0) {
this._sound.stop();
}
};
StopSoundAction2.prototype.serialize = function(parent) {
return _super.prototype._serialize.call(this, {
name: "StopSoundAction",
properties: [{ name: "sound", value: this._sound.name }]
}, parent);
};
return StopSoundAction2;
}(BABYLON2.Action)
);
BABYLON2.StopSoundAction = StopSoundAction;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var CubeTexture = (
/** @class */
function(_super) {
__extends(CubeTexture2, _super);
function CubeTexture2(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
if (extensions === void 0) {
extensions = null;
}
if (noMipmap === void 0) {
noMipmap = false;
}
if (files === void 0) {
files = null;
}
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (format === void 0) {
format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
}
if (prefiltered === void 0) {
prefiltered = false;
}
if (forcedExtension === void 0) {
forcedExtension = null;
}
if (createPolynomials === void 0) {
createPolynomials = false;
}
if (lodScale === void 0) {
lodScale = 0.8;
}
if (lodOffset === void 0) {
lodOffset = 0;
}
var _this = _super.call(this, scene) || this;
_this.boundingBoxPosition = BABYLON2.Vector3.Zero();
_this._rotationY = 0;
_this._prefiltered = false;
_this.name = rootUrl;
_this.url = rootUrl;
_this._noMipmap = noMipmap;
_this.hasAlpha = false;
_this._format = format;
_this.isCube = true;
_this._textureMatrix = BABYLON2.Matrix.Identity();
_this._createPolynomials = createPolynomials;
_this.coordinatesMode = BABYLON2.Texture.CUBIC_MODE;
if (!rootUrl && !files) {
return _this;
}
var lastDot = rootUrl.lastIndexOf(".");
var extension = forcedExtension ? forcedExtension : lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "";
var isDDS = extension === ".dds";
var isEnv = extension === ".env";
if (isEnv) {
_this.gammaSpace = false;
_this._prefiltered = false;
} else {
_this._prefiltered = prefiltered;
if (prefiltered) {
_this.gammaSpace = false;
}
}
_this._texture = _this._getFromCache(rootUrl, noMipmap);
if (!files) {
if (!isEnv && !isDDS && !extensions) {
extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
}
files = [];
if (extensions) {
for (var index = 0; index < extensions.length; index++) {
files.push(rootUrl + extensions[index]);
}
}
}
_this._files = files;
if (!_this._texture) {
if (!scene.useDelayedTextureLoading) {
if (prefiltered) {
_this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
} else {
_this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
}
} else {
_this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED;
}
} else if (onLoad) {
if (_this._texture.isReady) {
BABYLON2.Tools.SetImmediate(function() {
return onLoad();
});
} else {
_this._texture.onLoadedObservable.add(onLoad);
}
}
return _this;
}
Object.defineProperty(CubeTexture2.prototype, "boundingBoxSize", {
/**
* Returns the bounding box size
* @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
*/
get: function() {
return this._boundingBoxSize;
},
/**
* Gets or sets the size of the bounding box associated with the cube texture
* When defined, the cubemap will switch to local mode
* @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
* @example https://www.babylonjs-playground.com/#RNASML
*/
set: function(value) {
if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
return;
}
this._boundingBoxSize = value;
var scene = this.getScene();
if (scene) {
scene.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(CubeTexture2.prototype, "rotationY", {
/**
* Gets texture matrix rotation angle around Y axis radians.
*/
get: function() {
return this._rotationY;
},
/**
* Sets texture matrix rotation angle around Y axis in radians.
*/
set: function(value) {
this._rotationY = value;
this.setReflectionTextureMatrix(BABYLON2.Matrix.RotationY(this._rotationY));
},
enumerable: true,
configurable: true
});
CubeTexture2.CreateFromImages = function(files, scene, noMipmap) {
var rootUrlKey = "";
files.forEach(function(url) {
return rootUrlKey += url;
});
return new CubeTexture2(rootUrlKey, scene, null, noMipmap, files);
};
CubeTexture2.CreateFromPrefilteredData = function(url, scene, forcedExtension, createPolynomials) {
if (forcedExtension === void 0) {
forcedExtension = null;
}
if (createPolynomials === void 0) {
createPolynomials = true;
}
return new CubeTexture2(url, scene, null, false, null, null, null, void 0, true, forcedExtension, createPolynomials);
};
CubeTexture2.prototype.delayLoad = function() {
if (this.delayLoadState !== BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED) {
return;
}
var scene = this.getScene();
if (!scene) {
return;
}
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADED;
this._texture = this._getFromCache(this.url, this._noMipmap);
if (!this._texture) {
if (this._prefiltered) {
this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, void 0, void 0, this._format, void 0, this._createPolynomials);
} else {
this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, void 0, void 0, this._format);
}
}
};
CubeTexture2.prototype.getReflectionTextureMatrix = function() {
return this._textureMatrix;
};
CubeTexture2.prototype.setReflectionTextureMatrix = function(value) {
this._textureMatrix = value;
};
CubeTexture2.Parse = function(parsedTexture, scene, rootUrl) {
var texture = BABYLON2.SerializationHelper.Parse(function() {
var prefiltered = false;
if (parsedTexture.prefiltered) {
prefiltered = parsedTexture.prefiltered;
}
return new CubeTexture2(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, void 0, prefiltered);
}, parsedTexture, scene);
if (parsedTexture.boundingBoxPosition) {
texture.boundingBoxPosition = BABYLON2.Vector3.FromArray(parsedTexture.boundingBoxPosition);
}
if (parsedTexture.boundingBoxSize) {
texture.boundingBoxSize = BABYLON2.Vector3.FromArray(parsedTexture.boundingBoxSize);
}
if (parsedTexture.animations) {
for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
var parsedAnimation = parsedTexture.animations[animationIndex];
texture.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
}
return texture;
};
CubeTexture2.prototype.clone = function() {
var _this = this;
return BABYLON2.SerializationHelper.Clone(function() {
var scene = _this.getScene();
if (!scene) {
return _this;
}
return new CubeTexture2(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
}, this);
};
__decorate([
BABYLON2.serialize("rotationY")
], CubeTexture2.prototype, "rotationY", null);
return CubeTexture2;
}(BABYLON2.BaseTexture)
);
BABYLON2.CubeTexture = CubeTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RawCubeTexture = (
/** @class */
function(_super) {
__extends(RawCubeTexture2, _super);
function RawCubeTexture2(scene, data2, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
if (format === void 0) {
format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
}
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (generateMipMaps === void 0) {
generateMipMaps = false;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (compression === void 0) {
compression = null;
}
var _this = _super.call(this, "", scene) || this;
_this._texture = scene.getEngine().createRawCubeTexture(data2, size, format, type, generateMipMaps, invertY, samplingMode, compression);
return _this;
}
RawCubeTexture2.prototype.update = function(data2, format, type, invertY, compression, level) {
if (compression === void 0) {
compression = null;
}
if (level === void 0) {
level = 0;
}
this._texture.getEngine().updateRawCubeTexture(this._texture, data2, format, type, invertY, compression);
};
RawCubeTexture2.prototype.updateRGBDAsync = function(data2, sphericalPolynomial, lodScale, lodOffset) {
if (sphericalPolynomial === void 0) {
sphericalPolynomial = null;
}
if (lodScale === void 0) {
lodScale = 0.8;
}
if (lodOffset === void 0) {
lodOffset = 0;
}
return RawCubeTexture2._UpdateRGBDAsync(this._texture, data2, sphericalPolynomial, lodScale, lodOffset);
};
RawCubeTexture2.prototype.clone = function() {
var _this = this;
return BABYLON2.SerializationHelper.Clone(function() {
var scene = _this.getScene();
var internalTexture = _this._texture;
var texture = new RawCubeTexture2(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
if (internalTexture.dataSource === BABYLON2.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
}
return texture;
}, this);
};
RawCubeTexture2._UpdateRGBDAsync = function(internalTexture, data2, sphericalPolynomial, lodScale, lodOffset) {
internalTexture._dataSource = BABYLON2.InternalTexture.DATASOURCE_CUBERAW_RGBD;
internalTexture._bufferViewArrayArray = data2;
internalTexture._lodGenerationScale = lodScale;
internalTexture._lodGenerationOffset = lodOffset;
internalTexture._sphericalPolynomial = sphericalPolynomial;
return BABYLON2.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data2).then(function() {
internalTexture.isReady = true;
});
};
return RawCubeTexture2;
}(BABYLON2.CubeTexture)
);
BABYLON2.RawCubeTexture = RawCubeTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RenderTargetTexture = (
/** @class */
function(_super) {
__extends(RenderTargetTexture2, _super);
function RenderTargetTexture2(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
if (doNotChangeAspectRatio === void 0) {
doNotChangeAspectRatio = true;
}
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (isCube === void 0) {
isCube = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (generateDepthBuffer === void 0) {
generateDepthBuffer = true;
}
if (generateStencilBuffer === void 0) {
generateStencilBuffer = false;
}
if (isMulti === void 0) {
isMulti = false;
}
if (format === void 0) {
format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
}
var _this = _super.call(this, null, scene, !generateMipMaps) || this;
_this.isCube = isCube;
_this.renderParticles = true;
_this.renderSprites = false;
_this.coordinatesMode = BABYLON2.Texture.PROJECTION_MODE;
_this.ignoreCameraViewport = false;
_this.onBeforeBindObservable = new BABYLON2.Observable();
_this.onAfterUnbindObservable = new BABYLON2.Observable();
_this.onBeforeRenderObservable = new BABYLON2.Observable();
_this.onAfterRenderObservable = new BABYLON2.Observable();
_this.onClearObservable = new BABYLON2.Observable();
_this._currentRefreshId = -1;
_this._refreshRate = 1;
_this._samples = 1;
_this.boundingBoxPosition = BABYLON2.Vector3.Zero();
scene = _this.getScene();
if (!scene) {
return _this;
}
_this.renderList = new Array();
_this._engine = scene.getEngine();
_this.name = name;
_this.isRenderTarget = true;
_this._initialSizeParameter = size;
_this._processSizeParameter(size);
_this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function() {
});
_this._generateMipMaps = generateMipMaps ? true : false;
_this._doNotChangeAspectRatio = doNotChangeAspectRatio;
_this._renderingManager = new BABYLON2.RenderingManager(scene);
_this._renderingManager._useSceneAutoClearSetup = true;
if (isMulti) {
return _this;
}
_this._renderTargetOptions = {
generateMipMaps,
type,
format,
samplingMode,
generateDepthBuffer,
generateStencilBuffer
};
if (samplingMode === BABYLON2.Texture.NEAREST_SAMPLINGMODE) {
_this.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
}
if (isCube) {
_this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
_this.coordinatesMode = BABYLON2.Texture.INVCUBIC_MODE;
_this._textureMatrix = BABYLON2.Matrix.Identity();
} else {
_this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
}
return _this;
}
Object.defineProperty(RenderTargetTexture2.prototype, "renderList", {
/**
* Use this list to define the list of mesh you want to render.
*/
get: function() {
return this._renderList;
},
set: function(value) {
this._renderList = value;
if (this._renderList) {
this._hookArray(this._renderList);
}
},
enumerable: true,
configurable: true
});
RenderTargetTexture2.prototype._hookArray = function(array) {
var _this = this;
var oldPush = array.push;
array.push = function() {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var wasEmpty = array.length === 0;
var result = oldPush.apply(array, items);
if (wasEmpty) {
_this.getScene().meshes.forEach(function(mesh2) {
mesh2._markSubMeshesAsLightDirty();
});
}
return result;
};
var oldSplice = array.splice;
array.splice = function(index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
if (array.length === 0) {
_this.getScene().meshes.forEach(function(mesh2) {
mesh2._markSubMeshesAsLightDirty();
});
}
return deleted;
};
};
Object.defineProperty(RenderTargetTexture2.prototype, "onAfterUnbind", {
/**
* Set a after unbind callback in the texture.
* This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
*/
set: function(callback) {
if (this._onAfterUnbindObserver) {
this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
}
this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderTargetTexture2.prototype, "onBeforeRender", {
/**
* Set a before render callback in the texture.
* This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
*/
set: function(callback) {
if (this._onBeforeRenderObserver) {
this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
}
this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderTargetTexture2.prototype, "onAfterRender", {
/**
* Set a after render callback in the texture.
* This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
*/
set: function(callback) {
if (this._onAfterRenderObserver) {
this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
}
this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderTargetTexture2.prototype, "onClear", {
/**
* Set a clear callback in the texture.
* This has been kept for backward compatibility and use of onClearObservable is recommended.
*/
set: function(callback) {
if (this._onClearObserver) {
this.onClearObservable.remove(this._onClearObserver);
}
this._onClearObserver = this.onClearObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RenderTargetTexture2.prototype, "renderTargetOptions", {
/**
* Gets render target creation options that were used.
*/
get: function() {
return this._renderTargetOptions;
},
enumerable: true,
configurable: true
});
RenderTargetTexture2.prototype._onRatioRescale = function() {
if (this._sizeRatio) {
this.resize(this._initialSizeParameter);
}
};
Object.defineProperty(RenderTargetTexture2.prototype, "boundingBoxSize", {
get: function() {
return this._boundingBoxSize;
},
/**
* Gets or sets the size of the bounding box associated with the texture (when in cube mode)
* When defined, the cubemap will switch to local mode
* @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
* @example https://www.babylonjs-playground.com/#RNASML
*/
set: function(value) {
if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
return;
}
this._boundingBoxSize = value;
var scene = this.getScene();
if (scene) {
scene.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
}
},
enumerable: true,
configurable: true
});
RenderTargetTexture2.prototype.createDepthStencilTexture = function(comparisonFunction, bilinearFiltering, generateStencil) {
if (comparisonFunction === void 0) {
comparisonFunction = 0;
}
if (bilinearFiltering === void 0) {
bilinearFiltering = true;
}
if (generateStencil === void 0) {
generateStencil = false;
}
if (!this.getScene()) {
return;
}
var engine = this.getScene().getEngine();
this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
bilinearFiltering,
comparisonFunction,
generateStencil,
isCube: this.isCube
});
engine.setFrameBufferDepthStencilTexture(this);
};
RenderTargetTexture2.prototype._processSizeParameter = function(size) {
if (size.ratio) {
this._sizeRatio = size.ratio;
this._size = {
width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
};
} else {
this._size = size;
}
};
Object.defineProperty(RenderTargetTexture2.prototype, "samples", {
/**
* Define the number of samples to use in case of MSAA.
* It defaults to one meaning no MSAA has been enabled.
*/
get: function() {
return this._samples;
},
set: function(value) {
if (this._samples === value) {
return;
}
var scene = this.getScene();
if (!scene) {
return;
}
this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
},
enumerable: true,
configurable: true
});
RenderTargetTexture2.prototype.resetRefreshCounter = function() {
this._currentRefreshId = -1;
};
Object.defineProperty(RenderTargetTexture2.prototype, "refreshRate", {
/**
* Define the refresh rate of the texture or the rendering frequency.
* Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
*/
get: function() {
return this._refreshRate;
},
set: function(value) {
this._refreshRate = value;
this.resetRefreshCounter();
},
enumerable: true,
configurable: true
});
RenderTargetTexture2.prototype.addPostProcess = function(postProcess) {
if (!this._postProcessManager) {
var scene = this.getScene();
if (!scene) {
return;
}
this._postProcessManager = new BABYLON2.PostProcessManager(scene);
this._postProcesses = new Array();
}
this._postProcesses.push(postProcess);
this._postProcesses[0].autoClear = false;
};
RenderTargetTexture2.prototype.clearPostProcesses = function(dispose) {
if (dispose === void 0) {
dispose = false;
}
if (!this._postProcesses) {
return;
}
if (dispose) {
for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
var postProcess = _a[_i];
postProcess.dispose();
}
}
this._postProcesses = [];
};
RenderTargetTexture2.prototype.removePostProcess = function(postProcess) {
if (!this._postProcesses) {
return;
}
var index = this._postProcesses.indexOf(postProcess);
if (index === -1) {
return;
}
this._postProcesses.splice(index, 1);
if (this._postProcesses.length > 0) {
this._postProcesses[0].autoClear = false;
}
};
RenderTargetTexture2.prototype._shouldRender = function() {
if (this._currentRefreshId === -1) {
this._currentRefreshId = 1;
return true;
}
if (this.refreshRate === this._currentRefreshId) {
this._currentRefreshId = 1;
return true;
}
this._currentRefreshId++;
return false;
};
RenderTargetTexture2.prototype.getRenderSize = function() {
return this.getRenderWidth();
};
RenderTargetTexture2.prototype.getRenderWidth = function() {
if (this._size.width) {
return this._size.width;
}
return this._size;
};
RenderTargetTexture2.prototype.getRenderHeight = function() {
if (this._size.width) {
return this._size.height;
}
return this._size;
};
Object.defineProperty(RenderTargetTexture2.prototype, "canRescale", {
/**
* Get if the texture can be rescaled or not.
*/
get: function() {
return true;
},
enumerable: true,
configurable: true
});
RenderTargetTexture2.prototype.scale = function(ratio) {
var newSize = this.getRenderSize() * ratio;
this.resize(newSize);
};
RenderTargetTexture2.prototype.getReflectionTextureMatrix = function() {
if (this.isCube) {
return this._textureMatrix;
}
return _super.prototype.getReflectionTextureMatrix.call(this);
};
RenderTargetTexture2.prototype.resize = function(size) {
this.releaseInternalTexture();
var scene = this.getScene();
if (!scene) {
return;
}
this._processSizeParameter(size);
if (this.isCube) {
this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
} else {
this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
}
};
RenderTargetTexture2.prototype.render = function(useCameraPostProcess, dumpForDebug) {
if (useCameraPostProcess === void 0) {
useCameraPostProcess = false;
}
if (dumpForDebug === void 0) {
dumpForDebug = false;
}
var scene = this.getScene();
if (!scene) {
return;
}
var engine = scene.getEngine();
if (this.useCameraPostProcesses !== void 0) {
useCameraPostProcess = this.useCameraPostProcesses;
}
if (this._waitingRenderList) {
this.renderList = [];
for (var index = 0; index < this._waitingRenderList.length; index++) {
var id = this._waitingRenderList[index];
var mesh_1 = scene.getMeshByID(id);
if (mesh_1) {
this.renderList.push(mesh_1);
}
}
delete this._waitingRenderList;
}
if (this.renderListPredicate) {
if (this.renderList) {
this.renderList.splice(0);
} else {
this.renderList = [];
}
var scene = this.getScene();
if (!scene) {
return;
}
var sceneMeshes = scene.meshes;
for (var index = 0; index < sceneMeshes.length; index++) {
var mesh2 = sceneMeshes[index];
if (this.renderListPredicate(mesh2)) {
this.renderList.push(mesh2);
}
}
}
this.onBeforeBindObservable.notifyObservers(this);
var camera2;
if (this.activeCamera) {
camera2 = this.activeCamera;
engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
if (this.activeCamera !== scene.activeCamera) {
scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
}
} else {
camera2 = scene.activeCamera;
if (camera2) {
engine.setViewport(camera2.viewport, this.getRenderWidth(), this.getRenderHeight());
}
}
this._renderingManager.reset();
var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
var sceneRenderId = scene.getRenderId();
for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
var mesh2 = currentRenderList[meshIndex];
if (mesh2) {
if (!mesh2.isReady(this.refreshRate === 0)) {
this.resetRefreshCounter();
continue;
}
mesh2._preActivateForIntermediateRendering(sceneRenderId);
var isMasked = void 0;
if (!this.renderList && camera2) {
isMasked = (mesh2.layerMask & camera2.layerMask) === 0;
} else {
isMasked = false;
}
if (mesh2.isEnabled() && mesh2.isVisible && mesh2.subMeshes && !isMasked) {
mesh2._activate(sceneRenderId);
for (var subIndex = 0; subIndex < mesh2.subMeshes.length; subIndex++) {
var subMesh = mesh2.subMeshes[subIndex];
scene._activeIndices.addCount(subMesh.indexCount, false);
this._renderingManager.dispatch(subMesh, mesh2);
}
}
}
}
for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
var particleSystem = scene.particleSystems[particleIndex];
var emitter = particleSystem.emitter;
if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
continue;
}
if (currentRenderList.indexOf(emitter) >= 0) {
this._renderingManager.dispatchParticles(particleSystem);
}
}
if (this.isCube) {
for (var face = 0; face < 6; face++) {
this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
scene.incrementRenderId();
scene.resetCachedMaterial();
}
} else {
this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
}
this.onAfterUnbindObservable.notifyObservers(this);
if (scene.activeCamera) {
if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
}
engine.setViewport(scene.activeCamera.viewport);
}
scene.resetCachedMaterial();
};
RenderTargetTexture2.prototype._bestReflectionRenderTargetDimension = function(renderDimension, scale) {
var minimum = 128;
var x = renderDimension * scale;
var curved = BABYLON2.Tools.NearestPOT(x + minimum * minimum / (minimum + x));
return Math.min(BABYLON2.Tools.FloorPOT(renderDimension), curved);
};
RenderTargetTexture2.prototype.unbindFrameBuffer = function(engine, faceIndex) {
var _this = this;
if (!this._texture) {
return;
}
engine.unBindFramebuffer(this._texture, this.isCube, function() {
_this.onAfterRenderObservable.notifyObservers(faceIndex);
});
};
RenderTargetTexture2.prototype.renderToTarget = function(faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
var scene = this.getScene();
if (!scene) {
return;
}
var engine = scene.getEngine();
if (!this._texture) {
return;
}
if (this._postProcessManager) {
this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
} else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
if (this._texture) {
engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : void 0, void 0, void 0, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : void 0);
}
}
this.onBeforeRenderObservable.notifyObservers(faceIndex);
if (this.onClearObservable.hasObservers()) {
this.onClearObservable.notifyObservers(engine);
} else {
engine.clear(this.clearColor || scene.clearColor, true, true, true);
}
if (!this._doNotChangeAspectRatio) {
scene.updateTransformMatrix(true);
}
this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
if (this._postProcessManager) {
this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
} else if (useCameraPostProcess) {
scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
}
if (!this._doNotChangeAspectRatio) {
scene.updateTransformMatrix(true);
}
if (dumpForDebug) {
BABYLON2.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
}
if (!this.isCube || faceIndex === 5) {
if (this.isCube) {
if (faceIndex === 5) {
engine.generateMipMapsForCubemap(this._texture);
}
}
this.unbindFrameBuffer(engine, faceIndex);
} else {
this.onAfterRenderObservable.notifyObservers(faceIndex);
}
};
RenderTargetTexture2.prototype.setRenderingOrder = function(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
if (opaqueSortCompareFn === void 0) {
opaqueSortCompareFn = null;
}
if (alphaTestSortCompareFn === void 0) {
alphaTestSortCompareFn = null;
}
if (transparentSortCompareFn === void 0) {
transparentSortCompareFn = null;
}
this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
};
RenderTargetTexture2.prototype.setRenderingAutoClearDepthStencil = function(renderingGroupId, autoClearDepthStencil) {
this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
this._renderingManager._useSceneAutoClearSetup = false;
};
RenderTargetTexture2.prototype.clone = function() {
var textureSize = this.getSize();
var newTexture = new RenderTargetTexture2(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
newTexture.hasAlpha = this.hasAlpha;
newTexture.level = this.level;
newTexture.coordinatesMode = this.coordinatesMode;
if (this.renderList) {
newTexture.renderList = this.renderList.slice(0);
}
return newTexture;
};
RenderTargetTexture2.prototype.serialize = function() {
if (!this.name) {
return null;
}
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.renderTargetSize = this.getRenderSize();
serializationObject.renderList = [];
if (this.renderList) {
for (var index = 0; index < this.renderList.length; index++) {
serializationObject.renderList.push(this.renderList[index].id);
}
}
return serializationObject;
};
RenderTargetTexture2.prototype.disposeFramebufferObjects = function() {
var objBuffer = this.getInternalTexture();
var scene = this.getScene();
if (objBuffer && scene) {
scene.getEngine()._releaseFramebufferObjects(objBuffer);
}
};
RenderTargetTexture2.prototype.dispose = function() {
if (this._postProcessManager) {
this._postProcessManager.dispose();
this._postProcessManager = null;
}
this.clearPostProcesses(true);
if (this._resizeObserver) {
this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
this._resizeObserver = null;
}
this.renderList = null;
var scene = this.getScene();
if (!scene) {
return;
}
var index = scene.customRenderTargets.indexOf(this);
if (index >= 0) {
scene.customRenderTargets.splice(index, 1);
}
for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
var camera2 = _a[_i];
index = camera2.customRenderTargets.indexOf(this);
if (index >= 0) {
camera2.customRenderTargets.splice(index, 1);
}
}
_super.prototype.dispose.call(this);
};
RenderTargetTexture2.prototype._rebuild = function() {
if (this.refreshRate === RenderTargetTexture2.REFRESHRATE_RENDER_ONCE) {
this.refreshRate = RenderTargetTexture2.REFRESHRATE_RENDER_ONCE;
}
if (this._postProcessManager) {
this._postProcessManager._rebuild();
}
};
RenderTargetTexture2.prototype.freeRenderingGroups = function() {
if (this._renderingManager) {
this._renderingManager.freeRenderingGroups();
}
};
RenderTargetTexture2.REFRESHRATE_RENDER_ONCE = 0;
RenderTargetTexture2.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
RenderTargetTexture2.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
return RenderTargetTexture2;
}(BABYLON2.Texture)
);
BABYLON2.RenderTargetTexture = RenderTargetTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MultiRenderTarget = (
/** @class */
function(_super) {
__extends(MultiRenderTarget2, _super);
function MultiRenderTarget2(name, size, count, scene, options) {
var _this = this;
var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === void 0 ? true : options.doNotChangeAspectRatio;
_this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
_this._engine = scene.getEngine();
if (!_this.isSupported) {
_this.dispose();
return;
}
var types = [];
var samplingModes = [];
for (var i2 = 0; i2 < count; i2++) {
if (options && options.types && options.types[i2] !== void 0) {
types.push(options.types[i2]);
} else {
types.push(options && options.defaultType ? options.defaultType : BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
}
if (options && options.samplingModes && options.samplingModes[i2] !== void 0) {
samplingModes.push(options.samplingModes[i2]);
} else {
samplingModes.push(BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
}
}
var generateDepthBuffer = !options || options.generateDepthBuffer === void 0 ? true : options.generateDepthBuffer;
var generateStencilBuffer = !options || options.generateStencilBuffer === void 0 ? false : options.generateStencilBuffer;
_this._size = size;
_this._multiRenderTargetOptions = {
samplingModes,
generateMipMaps,
generateDepthBuffer,
generateStencilBuffer,
generateDepthTexture,
types,
textureCount: count
};
_this._createInternalTextures();
_this._createTextures();
return _this;
}
Object.defineProperty(MultiRenderTarget2.prototype, "isSupported", {
/**
* Get if draw buffers are currently supported by the used hardware and browser.
*/
get: function() {
return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiRenderTarget2.prototype, "textures", {
/**
* Get the list of textures generated by the multi render target.
*/
get: function() {
return this._textures;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiRenderTarget2.prototype, "depthTexture", {
/**
* Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
*/
get: function() {
return this._textures[this._textures.length - 1];
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiRenderTarget2.prototype, "wrapU", {
/**
* Set the wrapping mode on U of all the textures we are rendering to.
* Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
*/
set: function(wrap) {
if (this._textures) {
for (var i2 = 0; i2 < this._textures.length; i2++) {
this._textures[i2].wrapU = wrap;
}
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(MultiRenderTarget2.prototype, "wrapV", {
/**
* Set the wrapping mode on V of all the textures we are rendering to.
* Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
*/
set: function(wrap) {
if (this._textures) {
for (var i2 = 0; i2 < this._textures.length; i2++) {
this._textures[i2].wrapV = wrap;
}
}
},
enumerable: true,
configurable: true
});
MultiRenderTarget2.prototype._rebuild = function() {
this.releaseInternalTextures();
this._createInternalTextures();
for (var i2 = 0; i2 < this._internalTextures.length; i2++) {
var texture = this._textures[i2];
texture._texture = this._internalTextures[i2];
}
this._texture = this._internalTextures[0];
};
MultiRenderTarget2.prototype._createInternalTextures = function() {
this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
};
MultiRenderTarget2.prototype._createTextures = function() {
this._textures = [];
for (var i2 = 0; i2 < this._internalTextures.length; i2++) {
var texture = new BABYLON2.Texture(null, this.getScene());
texture._texture = this._internalTextures[i2];
this._textures.push(texture);
}
this._texture = this._internalTextures[0];
};
Object.defineProperty(MultiRenderTarget2.prototype, "samples", {
/**
* Define the number of samples used if MSAA is enabled.
*/
get: function() {
return this._samples;
},
set: function(value) {
if (this._samples === value) {
return;
}
this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
},
enumerable: true,
configurable: true
});
MultiRenderTarget2.prototype.resize = function(size) {
this.releaseInternalTextures();
this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
this._createInternalTextures();
};
MultiRenderTarget2.prototype.unbindFrameBuffer = function(engine, faceIndex) {
var _this = this;
engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function() {
_this.onAfterRenderObservable.notifyObservers(faceIndex);
});
};
MultiRenderTarget2.prototype.dispose = function() {
this.releaseInternalTextures();
_super.prototype.dispose.call(this);
};
MultiRenderTarget2.prototype.releaseInternalTextures = function() {
if (!this._internalTextures) {
return;
}
for (var i2 = this._internalTextures.length - 1; i2 >= 0; i2--) {
if (this._internalTextures[i2] !== void 0) {
this._internalTextures[i2].dispose();
this._internalTextures.splice(i2, 1);
}
}
};
return MultiRenderTarget2;
}(BABYLON2.RenderTargetTexture)
);
BABYLON2.MultiRenderTarget = MultiRenderTarget;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MirrorTexture = (
/** @class */
function(_super) {
__extends(MirrorTexture2, _super);
function MirrorTexture2(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.BILINEAR_SAMPLINGMODE;
}
if (generateDepthBuffer === void 0) {
generateDepthBuffer = true;
}
var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
_this.scene = scene;
_this.mirrorPlane = new BABYLON2.Plane(0, 1, 0, 1);
_this._transformMatrix = BABYLON2.Matrix.Zero();
_this._mirrorMatrix = BABYLON2.Matrix.Zero();
_this._adaptiveBlurKernel = 0;
_this._blurKernelX = 0;
_this._blurKernelY = 0;
_this._blurRatio = 1;
_this.ignoreCameraViewport = true;
_this._updateGammaSpace();
_this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function() {
_this._updateGammaSpace;
});
_this.onBeforeRenderObservable.add(function() {
BABYLON2.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
_this._savedViewMatrix = scene.getViewMatrix();
_this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
scene.clipPlane = _this.mirrorPlane;
scene.getEngine().cullBackFaces = false;
scene._mirroredCameraPosition = BABYLON2.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
});
_this.onAfterRenderObservable.add(function() {
scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
scene.getEngine().cullBackFaces = true;
scene._mirroredCameraPosition = null;
delete scene.clipPlane;
});
return _this;
}
Object.defineProperty(MirrorTexture2.prototype, "blurRatio", {
get: function() {
return this._blurRatio;
},
/**
* Define the blur ratio used to blur the reflection if needed.
*/
set: function(value) {
if (this._blurRatio === value) {
return;
}
this._blurRatio = value;
this._preparePostProcesses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(MirrorTexture2.prototype, "adaptiveBlurKernel", {
/**
* Define the adaptive blur kernel used to blur the reflection if needed.
* This will autocompute the closest best match for the `blurKernel`
*/
set: function(value) {
this._adaptiveBlurKernel = value;
this._autoComputeBlurKernel();
},
enumerable: true,
configurable: true
});
Object.defineProperty(MirrorTexture2.prototype, "blurKernel", {
/**
* Define the blur kernel used to blur the reflection if needed.
* Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
*/
set: function(value) {
this.blurKernelX = value;
this.blurKernelY = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MirrorTexture2.prototype, "blurKernelX", {
get: function() {
return this._blurKernelX;
},
/**
* Define the blur kernel on the X Axis used to blur the reflection if needed.
* Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
*/
set: function(value) {
if (this._blurKernelX === value) {
return;
}
this._blurKernelX = value;
this._preparePostProcesses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(MirrorTexture2.prototype, "blurKernelY", {
get: function() {
return this._blurKernelY;
},
/**
* Define the blur kernel on the Y Axis used to blur the reflection if needed.
* Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
*/
set: function(value) {
if (this._blurKernelY === value) {
return;
}
this._blurKernelY = value;
this._preparePostProcesses();
},
enumerable: true,
configurable: true
});
MirrorTexture2.prototype._autoComputeBlurKernel = function() {
var engine = this.getScene().getEngine();
var dw = this.getRenderWidth() / engine.getRenderWidth();
var dh = this.getRenderHeight() / engine.getRenderHeight();
this.blurKernelX = this._adaptiveBlurKernel * dw;
this.blurKernelY = this._adaptiveBlurKernel * dh;
};
MirrorTexture2.prototype._onRatioRescale = function() {
if (this._sizeRatio) {
this.resize(this._initialSizeParameter);
if (!this._adaptiveBlurKernel) {
this._preparePostProcesses();
}
}
if (this._adaptiveBlurKernel) {
this._autoComputeBlurKernel();
}
};
MirrorTexture2.prototype._updateGammaSpace = function() {
this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
};
MirrorTexture2.prototype._preparePostProcesses = function() {
this.clearPostProcesses(true);
if (this._blurKernelX && this._blurKernelY) {
var engine = this.getScene().getEngine();
var textureType = engine.getCaps().textureFloatRender ? BABYLON2.Engine.TEXTURETYPE_FLOAT : BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
this._blurX = new BABYLON2.BlurPostProcess("horizontal blur", new BABYLON2.Vector2(1, 0), this._blurKernelX, this._blurRatio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
this._blurX.autoClear = false;
if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
this._blurX.inputTexture = this._texture;
} else {
this._blurX.alwaysForcePOT = true;
}
this._blurY = new BABYLON2.BlurPostProcess("vertical blur", new BABYLON2.Vector2(0, 1), this._blurKernelY, this._blurRatio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
this._blurY.autoClear = false;
this._blurY.alwaysForcePOT = this._blurRatio !== 1;
this.addPostProcess(this._blurX);
this.addPostProcess(this._blurY);
} else {
if (this._blurY) {
this.removePostProcess(this._blurY);
this._blurY.dispose();
this._blurY = null;
}
if (this._blurX) {
this.removePostProcess(this._blurX);
this._blurX.dispose();
this._blurX = null;
}
}
};
MirrorTexture2.prototype.clone = function() {
var scene = this.getScene();
if (!scene) {
return this;
}
var textureSize = this.getSize();
var newTexture = new MirrorTexture2(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
newTexture.hasAlpha = this.hasAlpha;
newTexture.level = this.level;
newTexture.mirrorPlane = this.mirrorPlane.clone();
if (this.renderList) {
newTexture.renderList = this.renderList.slice(0);
}
return newTexture;
};
MirrorTexture2.prototype.serialize = function() {
if (!this.name) {
return null;
}
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.mirrorPlane = this.mirrorPlane.asArray();
return serializationObject;
};
MirrorTexture2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
};
return MirrorTexture2;
}(BABYLON2.RenderTargetTexture)
);
BABYLON2.MirrorTexture = MirrorTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RefractionTexture = (
/** @class */
function(_super) {
__extends(RefractionTexture2, _super);
function RefractionTexture2(name, size, scene, generateMipMaps) {
var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
_this.refractionPlane = new BABYLON2.Plane(0, 1, 0, 1);
_this.depth = 2;
_this.onBeforeRenderObservable.add(function() {
scene.clipPlane = _this.refractionPlane;
});
_this.onAfterRenderObservable.add(function() {
delete scene.clipPlane;
});
return _this;
}
RefractionTexture2.prototype.clone = function() {
var scene = this.getScene();
if (!scene) {
return this;
}
var textureSize = this.getSize();
var newTexture = new RefractionTexture2(this.name, textureSize.width, scene, this._generateMipMaps);
newTexture.hasAlpha = this.hasAlpha;
newTexture.level = this.level;
newTexture.refractionPlane = this.refractionPlane.clone();
if (this.renderList) {
newTexture.renderList = this.renderList.slice(0);
}
newTexture.depth = this.depth;
return newTexture;
};
RefractionTexture2.prototype.serialize = function() {
if (!this.name) {
return null;
}
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.mirrorPlane = this.refractionPlane.asArray();
serializationObject.depth = this.depth;
return serializationObject;
};
return RefractionTexture2;
}(BABYLON2.RenderTargetTexture)
);
BABYLON2.RefractionTexture = RefractionTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DynamicTexture = (
/** @class */
function(_super) {
__extends(DynamicTexture2, _super);
function DynamicTexture2(name, options, scene, generateMipMaps, samplingMode, format) {
if (scene === void 0) {
scene = null;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (format === void 0) {
format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
}
var _this = _super.call(this, null, scene, !generateMipMaps, void 0, samplingMode, void 0, void 0, void 0, void 0, format) || this;
_this.name = name;
_this._engine = _this.getScene().getEngine();
_this.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this._generateMipMaps = generateMipMaps;
if (options.getContext) {
_this._canvas = options;
_this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
} else {
_this._canvas = document.createElement("canvas");
if (options.width || options.width === 0) {
_this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
} else {
_this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
}
}
var textureSize = _this.getSize();
_this._canvas.width = textureSize.width;
_this._canvas.height = textureSize.height;
_this._context = _this._canvas.getContext("2d");
return _this;
}
Object.defineProperty(DynamicTexture2.prototype, "canRescale", {
/**
* Gets the current state of canRescale
*/
get: function() {
return true;
},
enumerable: true,
configurable: true
});
DynamicTexture2.prototype._recreate = function(textureSize) {
this._canvas.width = textureSize.width;
this._canvas.height = textureSize.height;
this.releaseInternalTexture();
this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
};
DynamicTexture2.prototype.scale = function(ratio) {
var textureSize = this.getSize();
textureSize.width *= ratio;
textureSize.height *= ratio;
this._recreate(textureSize);
};
DynamicTexture2.prototype.scaleTo = function(width, height) {
var textureSize = this.getSize();
textureSize.width = width;
textureSize.height = height;
this._recreate(textureSize);
};
DynamicTexture2.prototype.getContext = function() {
return this._context;
};
DynamicTexture2.prototype.clear = function() {
var size = this.getSize();
this._context.fillRect(0, 0, size.width, size.height);
};
DynamicTexture2.prototype.update = function(invertY, premulAlpha) {
if (premulAlpha === void 0) {
premulAlpha = false;
}
this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === void 0 ? true : invertY, premulAlpha, this._format || void 0);
};
DynamicTexture2.prototype.drawText = function(text, x, y, font, color, clearColor, invertY, update) {
if (update === void 0) {
update = true;
}
var size = this.getSize();
if (clearColor) {
this._context.fillStyle = clearColor;
this._context.fillRect(0, 0, size.width, size.height);
}
this._context.font = font;
if (x === null || x === void 0) {
var textSize = this._context.measureText(text);
x = (size.width - textSize.width) / 2;
}
if (y === null || y === void 0) {
var fontSize = parseInt(font.replace(/\D/g, ""));
y = size.height / 2 + fontSize / 3.65;
}
this._context.fillStyle = color;
this._context.fillText(text, x, y);
if (update) {
this.update(invertY);
}
};
DynamicTexture2.prototype.clone = function() {
var scene = this.getScene();
if (!scene) {
return this;
}
var textureSize = this.getSize();
var newTexture = new DynamicTexture2(this.name, textureSize, scene, this._generateMipMaps);
newTexture.hasAlpha = this.hasAlpha;
newTexture.level = this.level;
newTexture.wrapU = this.wrapU;
newTexture.wrapV = this.wrapV;
return newTexture;
};
DynamicTexture2.prototype.serialize = function() {
var scene = this.getScene();
if (scene && !scene.isReady()) {
BABYLON2.Tools.Warn("The scene must be ready before serializing the dynamic texture");
}
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.base64String = this._canvas.toDataURL();
serializationObject.invertY = this._invertY;
serializationObject.samplingMode = this.samplingMode;
return serializationObject;
};
DynamicTexture2.prototype._rebuild = function() {
this.update();
};
return DynamicTexture2;
}(BABYLON2.Texture)
);
BABYLON2.DynamicTexture = DynamicTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var VideoTexture = (
/** @class */
function(_super) {
__extends(VideoTexture2, _super);
function VideoTexture2(name, src, scene, generateMipMaps, invertY, samplingMode, settings2) {
if (generateMipMaps === void 0) {
generateMipMaps = false;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (settings2 === void 0) {
settings2 = {
autoPlay: true,
loop: true,
autoUpdateTexture: true
};
}
var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
_this._onUserActionRequestedObservable = null;
_this._stillImageCaptured = false;
_this._poster = false;
_this._createInternalTexture = function() {
if (_this._texture != null) {
if (_this._poster) {
_this._texture.dispose();
_this._poster = false;
} else {
return;
}
}
if (!_this._engine.needPOTTextures || BABYLON2.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON2.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
_this.wrapU = BABYLON2.Texture.WRAP_ADDRESSMODE;
_this.wrapV = BABYLON2.Texture.WRAP_ADDRESSMODE;
} else {
_this.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this._generateMipMaps = false;
}
_this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
if (!_this.video.autoplay) {
var oldHandler_1 = _this.video.onplaying;
var error_1 = false;
_this.video.onplaying = function() {
_this.video.onplaying = oldHandler_1;
_this._texture.isReady = true;
_this._updateInternalTexture();
if (!error_1) {
_this.video.pause();
}
if (_this.onLoadObservable.hasObservers()) {
_this.onLoadObservable.notifyObservers(_this);
}
};
var playing = _this.video.play();
if (playing) {
playing.then(function() {
}).catch(function() {
error_1 = true;
if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
_this._onUserActionRequestedObservable.notifyObservers(_this);
}
});
} else {
_this.video.onplaying = oldHandler_1;
_this._texture.isReady = true;
_this._updateInternalTexture();
if (_this.onLoadObservable.hasObservers()) {
_this.onLoadObservable.notifyObservers(_this);
}
}
} else {
_this._texture.isReady = true;
_this._updateInternalTexture();
if (_this.onLoadObservable.hasObservers()) {
_this.onLoadObservable.notifyObservers(_this);
}
}
};
_this.reset = function() {
if (_this._texture == null) {
return;
}
if (!_this._poster) {
_this._texture.dispose();
_this._texture = null;
}
};
_this._updateInternalTexture = function(e2) {
if (_this._texture == null || !_this._texture.isReady) {
return;
}
if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
return;
}
_this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
};
_this._engine = _this.getScene().getEngine();
_this._generateMipMaps = generateMipMaps;
_this._samplingMode = samplingMode;
_this.autoUpdateTexture = settings2.autoUpdateTexture;
_this.name = name || _this._getName(src);
_this.video = _this._getVideo(src);
if (settings2.poster) {
_this.video.poster = settings2.poster;
}
if (settings2.autoPlay !== void 0) {
_this.video.autoplay = settings2.autoPlay;
}
if (settings2.loop !== void 0) {
_this.video.loop = settings2.loop;
}
_this.video.setAttribute("playsinline", "");
_this.video.addEventListener("canplay", _this._createInternalTexture);
_this.video.addEventListener("paused", _this._updateInternalTexture);
_this.video.addEventListener("seeked", _this._updateInternalTexture);
_this.video.addEventListener("emptied", _this.reset);
if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
_this._createInternalTexture();
}
if (settings2.poster) {
_this._texture = _this._engine.createTexture(settings2.poster, false, true, scene);
_this._poster = true;
}
return _this;
}
Object.defineProperty(VideoTexture2.prototype, "onUserActionRequestedObservable", {
/**
* Event triggerd when a dom action is required by the user to play the video.
* This happens due to recent changes in browser policies preventing video to auto start.
*/
get: function() {
if (!this._onUserActionRequestedObservable) {
this._onUserActionRequestedObservable = new BABYLON2.Observable();
}
return this._onUserActionRequestedObservable;
},
enumerable: true,
configurable: true
});
VideoTexture2.prototype._getName = function(src) {
if (src instanceof HTMLVideoElement) {
return src.currentSrc;
}
if (typeof src === "object") {
return src.toString();
}
return src;
};
VideoTexture2.prototype._getVideo = function(src) {
if (src instanceof HTMLVideoElement) {
BABYLON2.Tools.SetCorsBehavior(src.currentSrc, src);
return src;
}
var video = document.createElement("video");
if (typeof src === "string") {
BABYLON2.Tools.SetCorsBehavior(src, video);
video.src = src;
} else {
BABYLON2.Tools.SetCorsBehavior(src[0], video);
src.forEach(function(url) {
var source = document.createElement("source");
source.src = url;
video.appendChild(source);
});
}
return video;
};
VideoTexture2.prototype._rebuild = function() {
this.update();
};
VideoTexture2.prototype.update = function() {
if (!this.autoUpdateTexture) {
return;
}
this.updateTexture(true);
};
VideoTexture2.prototype.updateTexture = function(isVisible) {
if (!isVisible) {
return;
}
if (this.video.paused && this._stillImageCaptured) {
return;
}
this._stillImageCaptured = true;
this._updateInternalTexture();
};
VideoTexture2.prototype.updateURL = function(url) {
this.video.src = url;
};
VideoTexture2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
if (this._onUserActionRequestedObservable) {
this._onUserActionRequestedObservable.clear();
this._onUserActionRequestedObservable = null;
}
this.video.removeEventListener("canplay", this._createInternalTexture);
this.video.removeEventListener("paused", this._updateInternalTexture);
this.video.removeEventListener("seeked", this._updateInternalTexture);
this.video.removeEventListener("emptied", this.reset);
this.video.pause();
};
VideoTexture2.CreateFromWebCam = function(scene, onReady, constraints) {
var video = document.createElement("video");
video.setAttribute("autoplay", "");
video.setAttribute("muted", "");
video.setAttribute("playsinline", "");
var constraintsDeviceId;
if (constraints && constraints.deviceId) {
constraintsDeviceId = {
exact: constraints.deviceId
};
}
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({ video: constraints }).then(function(stream) {
if (video.mozSrcObject !== void 0) {
video.mozSrcObject = stream;
} else {
video.srcObject = stream;
}
var onPlaying = function() {
if (onReady) {
onReady(new VideoTexture2("video", video, scene, true, true));
}
video.removeEventListener("playing", onPlaying);
};
video.addEventListener("playing", onPlaying);
video.play();
}).catch(function(err) {
BABYLON2.Tools.Error(err.name);
});
} else {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({
video: {
deviceId: constraintsDeviceId,
width: {
min: constraints && constraints.minWidth || 256,
max: constraints && constraints.maxWidth || 640
},
height: {
min: constraints && constraints.minHeight || 256,
max: constraints && constraints.maxHeight || 480
}
}
}, function(stream) {
if (video.mozSrcObject !== void 0) {
video.mozSrcObject = stream;
} else {
video.src = window.URL && window.URL.createObjectURL(stream) || stream;
}
video.play();
if (onReady) {
onReady(new VideoTexture2("video", video, scene, true, true));
}
}, function(e2) {
BABYLON2.Tools.Error(e2.name);
});
}
}
};
return VideoTexture2;
}(BABYLON2.Texture)
);
BABYLON2.VideoTexture = VideoTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RawTexture = (
/** @class */
function(_super) {
__extends(RawTexture2, _super);
function RawTexture2(data2, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
_this.format = format;
_this._engine = scene.getEngine();
_this._texture = scene.getEngine().createRawTexture(data2, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
_this.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
return _this;
}
RawTexture2.prototype.update = function(data2) {
this._engine.updateRawTexture(this._texture, data2, this._texture.format, this._texture.invertY, void 0, this._texture.type);
};
RawTexture2.CreateLuminanceTexture = function(data2, width, height, scene, generateMipMaps, invertY, samplingMode) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
return new RawTexture2(data2, width, height, BABYLON2.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
};
RawTexture2.CreateLuminanceAlphaTexture = function(data2, width, height, scene, generateMipMaps, invertY, samplingMode) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
return new RawTexture2(data2, width, height, BABYLON2.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
};
RawTexture2.CreateAlphaTexture = function(data2, width, height, scene, generateMipMaps, invertY, samplingMode) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
return new RawTexture2(data2, width, height, BABYLON2.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
};
RawTexture2.CreateRGBTexture = function(data2, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
return new RawTexture2(data2, width, height, BABYLON2.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
};
RawTexture2.CreateRGBATexture = function(data2, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
return new RawTexture2(data2, width, height, BABYLON2.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
};
RawTexture2.CreateRTexture = function(data2, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_FLOAT;
}
return new RawTexture2(data2, width, height, BABYLON2.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
};
return RawTexture2;
}(BABYLON2.Texture)
);
BABYLON2.RawTexture = RawTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RawTexture3D = (
/** @class */
function(_super) {
__extends(RawTexture3D2, _super);
function RawTexture3D2(data2, width, height, depth, format, scene, generateMipMaps, invertY, samplingMode, textureType) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (invertY === void 0) {
invertY = false;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
_this.format = format;
_this._engine = scene.getEngine();
_this._texture = scene.getEngine().createRawTexture3D(data2, width, height, depth, format, generateMipMaps, invertY, samplingMode, void 0, textureType);
_this.is3D = true;
return _this;
}
RawTexture3D2.prototype.update = function(data2) {
if (!this._texture) {
return;
}
this._engine.updateRawTexture3D(this._texture, data2, this._texture.format, this._texture.invertY, void 0, this._texture.type);
};
return RawTexture3D2;
}(BABYLON2.Texture)
);
BABYLON2.RawTexture3D = RawTexture3D;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PostProcessManager = (
/** @class */
function() {
function PostProcessManager2(scene) {
this._vertexBuffers = {};
this._scene = scene;
}
PostProcessManager2.prototype._prepareBuffers = function() {
if (this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind]) {
return;
}
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = new BABYLON2.VertexBuffer(this._scene.getEngine(), vertices, BABYLON2.VertexBuffer.PositionKind, false, false, 2);
this._buildIndexBuffer();
};
PostProcessManager2.prototype._buildIndexBuffer = function() {
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
};
PostProcessManager2.prototype._rebuild = function() {
var vb = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (!vb) {
return;
}
vb._rebuild();
this._buildIndexBuffer();
};
PostProcessManager2.prototype._prepareFrame = function(sourceTexture, postProcesses) {
if (sourceTexture === void 0) {
sourceTexture = null;
}
if (postProcesses === void 0) {
postProcesses = null;
}
var camera2 = this._scene.activeCamera;
if (!camera2) {
return false;
}
var postProcesses = postProcesses || camera2._postProcesses.filter(function(pp) {
return pp != null;
});
if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
return false;
}
postProcesses[0].activate(camera2, sourceTexture, postProcesses !== null && postProcesses !== void 0);
return true;
};
PostProcessManager2.prototype.directRender = function(postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
if (targetTexture === void 0) {
targetTexture = null;
}
if (forceFullscreenViewport === void 0) {
forceFullscreenViewport = false;
}
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lodLevel === void 0) {
lodLevel = 0;
}
var engine = this._scene.getEngine();
for (var index = 0; index < postProcesses.length; index++) {
if (index < postProcesses.length - 1) {
postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
} else {
if (targetTexture) {
engine.bindFramebuffer(targetTexture, faceIndex, void 0, void 0, forceFullscreenViewport, void 0, lodLevel);
} else {
engine.restoreDefaultFramebuffer();
}
}
var pp = postProcesses[index];
var effect = pp.apply();
if (effect) {
pp.onBeforeRenderObservable.notifyObservers(effect);
this._prepareBuffers();
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
pp.onAfterRenderObservable.notifyObservers(effect);
}
}
engine.setDepthBuffer(true);
engine.setDepthWrite(true);
};
PostProcessManager2.prototype._finalizeFrame = function(doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
if (forceFullscreenViewport === void 0) {
forceFullscreenViewport = false;
}
var camera2 = this._scene.activeCamera;
if (!camera2) {
return;
}
postProcesses = postProcesses || camera2._postProcesses.filter(function(pp2) {
return pp2 != null;
});
if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
return;
}
var engine = this._scene.getEngine();
for (var index = 0, len = postProcesses.length; index < len; index++) {
var pp = postProcesses[index];
if (index < len - 1) {
pp._outputTexture = postProcesses[index + 1].activate(camera2, targetTexture);
} else {
if (targetTexture) {
engine.bindFramebuffer(targetTexture, faceIndex, void 0, void 0, forceFullscreenViewport);
pp._outputTexture = targetTexture;
} else {
engine.restoreDefaultFramebuffer();
pp._outputTexture = null;
}
}
if (doNotPresent) {
break;
}
var effect = pp.apply();
if (effect) {
pp.onBeforeRenderObservable.notifyObservers(effect);
this._prepareBuffers();
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
pp.onAfterRenderObservable.notifyObservers(effect);
}
}
engine.setDepthBuffer(true);
engine.setDepthWrite(true);
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
};
PostProcessManager2.prototype.dispose = function() {
var buffer = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (buffer) {
buffer.dispose();
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
};
return PostProcessManager2;
}()
);
BABYLON2.PostProcessManager = PostProcessManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PostProcess = (
/** @class */
function() {
function PostProcess2(name, fragmentUrl, parameters, samplers, options, camera2, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.NEAREST_SAMPLINGMODE;
}
if (defines === void 0) {
defines = null;
}
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (vertexUrl === void 0) {
vertexUrl = "postprocess";
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
this.name = name;
this.width = -1;
this.height = -1;
this._outputTexture = null;
this.autoClear = true;
this.alphaMode = BABYLON2.Engine.ALPHA_DISABLE;
this.animations = new Array();
this.enablePixelPerfectMode = false;
this.forceFullscreenViewport = true;
this.scaleMode = BABYLON2.Engine.SCALEMODE_FLOOR;
this.alwaysForcePOT = false;
this._samples = 1;
this.adaptScaleToCurrentViewport = false;
this._reusable = false;
this._textures = new BABYLON2.SmartArray(2);
this._currentRenderTextureInd = 0;
this._scaleRatio = new BABYLON2.Vector2(1, 1);
this._texelSize = BABYLON2.Vector2.Zero();
this.onActivateObservable = new BABYLON2.Observable();
this.onSizeChangedObservable = new BABYLON2.Observable();
this.onApplyObservable = new BABYLON2.Observable();
this.onBeforeRenderObservable = new BABYLON2.Observable();
this.onAfterRenderObservable = new BABYLON2.Observable();
if (camera2 != null) {
this._camera = camera2;
this._scene = camera2.getScene();
camera2.attachPostProcess(this);
this._engine = this._scene.getEngine();
this._scene.postProcesses.push(this);
} else if (engine) {
this._engine = engine;
this._engine.postProcesses.push(this);
}
this._options = options;
this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON2.Texture.NEAREST_SAMPLINGMODE;
this._reusable = reusable || false;
this._textureType = textureType;
this._samplers = samplers || [];
this._samplers.push("textureSampler");
this._fragmentUrl = fragmentUrl;
this._vertexUrl = vertexUrl;
this._parameters = parameters || [];
this._parameters.push("scale");
this._indexParameters = indexParameters;
if (!blockCompilation) {
this.updateEffect(defines);
}
}
Object.defineProperty(PostProcess2.prototype, "samples", {
/**
* Number of sample textures (default: 1)
*/
get: function() {
return this._samples;
},
set: function(n) {
var _this = this;
this._samples = n;
this._textures.forEach(function(texture) {
if (texture.samples !== _this._samples) {
_this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
}
});
},
enumerable: true,
configurable: true
});
Object.defineProperty(PostProcess2.prototype, "onActivate", {
/**
* A function that is added to the onActivateObservable
*/
set: function(callback) {
if (this._onActivateObserver) {
this.onActivateObservable.remove(this._onActivateObserver);
}
if (callback) {
this._onActivateObserver = this.onActivateObservable.add(callback);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(PostProcess2.prototype, "onSizeChanged", {
/**
* A function that is added to the onSizeChangedObservable
*/
set: function(callback) {
if (this._onSizeChangedObserver) {
this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
}
this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PostProcess2.prototype, "onApply", {
/**
* A function that is added to the onApplyObservable
*/
set: function(callback) {
if (this._onApplyObserver) {
this.onApplyObservable.remove(this._onApplyObserver);
}
this._onApplyObserver = this.onApplyObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PostProcess2.prototype, "onBeforeRender", {
/**
* A function that is added to the onBeforeRenderObservable
*/
set: function(callback) {
if (this._onBeforeRenderObserver) {
this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
}
this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PostProcess2.prototype, "onAfterRender", {
/**
* A function that is added to the onAfterRenderObservable
*/
set: function(callback) {
if (this._onAfterRenderObserver) {
this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
}
this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PostProcess2.prototype, "inputTexture", {
/**
* The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
* render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
*/
get: function() {
return this._textures.data[this._currentRenderTextureInd];
},
set: function(value) {
this._forcedOutputTexture = value;
},
enumerable: true,
configurable: true
});
PostProcess2.prototype.getCamera = function() {
return this._camera;
};
Object.defineProperty(PostProcess2.prototype, "texelSize", {
/**
* Gets the texel size of the postprocess.
* See https://en.wikipedia.org/wiki/Texel_(graphics)
*/
get: function() {
if (this._shareOutputWithPostProcess) {
return this._shareOutputWithPostProcess.texelSize;
}
if (this._forcedOutputTexture) {
this._texelSize.copyFromFloats(1 / this._forcedOutputTexture.width, 1 / this._forcedOutputTexture.height);
}
return this._texelSize;
},
enumerable: true,
configurable: true
});
PostProcess2.prototype.getEngine = function() {
return this._engine;
};
PostProcess2.prototype.getEffect = function() {
return this._effect;
};
PostProcess2.prototype.shareOutputWith = function(postProcess) {
this._disposeTextures();
this._shareOutputWithPostProcess = postProcess;
return this;
};
PostProcess2.prototype.useOwnOutput = function() {
if (this._textures.length == 0) {
this._textures = new BABYLON2.SmartArray(2);
}
this._shareOutputWithPostProcess = null;
};
PostProcess2.prototype.updateEffect = function(defines, uniforms, samplers, indexParameters, onCompiled, onError) {
if (defines === void 0) {
defines = null;
}
if (uniforms === void 0) {
uniforms = null;
}
if (samplers === void 0) {
samplers = null;
}
this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", void 0, onCompiled, onError, indexParameters || this._indexParameters);
};
PostProcess2.prototype.isReusable = function() {
return this._reusable;
};
PostProcess2.prototype.markTextureDirty = function() {
this.width = -1;
};
PostProcess2.prototype.activate = function(camera2, sourceTexture, forceDepthStencil) {
var _this = this;
if (sourceTexture === void 0) {
sourceTexture = null;
}
camera2 = camera2 || this._camera;
var scene = camera2.getScene();
var engine = scene.getEngine();
var maxSize = engine.getCaps().maxTextureSize;
var requiredWidth = (sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options | 0;
var requiredHeight = (sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options | 0;
var webVRCamera = camera2.parent;
if (webVRCamera && (webVRCamera.leftCamera == camera2 || webVRCamera.rightCamera == camera2)) {
requiredWidth /= 2;
}
var desiredWidth = this._options.width || requiredWidth;
var desiredHeight = this._options.height || requiredHeight;
if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
if (this.adaptScaleToCurrentViewport) {
var currentViewport = engine.currentViewport;
if (currentViewport) {
desiredWidth *= currentViewport.width;
desiredHeight *= currentViewport.height;
}
}
if (this.renderTargetSamplingMode === BABYLON2.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
if (!this._options.width) {
desiredWidth = engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
}
if (!this._options.height) {
desiredHeight = engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
}
}
if (this.width !== desiredWidth || this.height !== desiredHeight) {
if (this._textures.length > 0) {
for (var i2 = 0; i2 < this._textures.length; i2++) {
this._engine._releaseTexture(this._textures.data[i2]);
}
this._textures.reset();
}
this.width = desiredWidth;
this.height = desiredHeight;
var textureSize = { width: this.width, height: this.height };
var textureOptions = {
generateMipMaps: false,
generateDepthBuffer: forceDepthStencil || camera2._postProcesses.indexOf(this) === 0,
generateStencilBuffer: (forceDepthStencil || camera2._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
samplingMode: this.renderTargetSamplingMode,
type: this._textureType
};
this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
if (this._reusable) {
this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
}
this._texelSize.copyFromFloats(1 / this.width, 1 / this.height);
this.onSizeChangedObservable.notifyObservers(this);
}
this._textures.forEach(function(texture) {
if (texture.samples !== _this.samples) {
_this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
}
});
}
var target;
if (this._shareOutputWithPostProcess) {
target = this._shareOutputWithPostProcess.inputTexture;
} else if (this._forcedOutputTexture) {
target = this._forcedOutputTexture;
this.width = this._forcedOutputTexture.width;
this.height = this._forcedOutputTexture.height;
} else {
target = this.inputTexture;
}
if (this.enablePixelPerfectMode) {
this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
} else {
this._scaleRatio.copyFromFloats(1, 1);
this._engine.bindFramebuffer(target, 0, void 0, void 0, this.forceFullscreenViewport);
}
this.onActivateObservable.notifyObservers(camera2);
if (this.autoClear && this.alphaMode === BABYLON2.Engine.ALPHA_DISABLE) {
this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
}
if (this._reusable) {
this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
}
return target;
};
Object.defineProperty(PostProcess2.prototype, "isSupported", {
/**
* If the post process is supported.
*/
get: function() {
return this._effect.isSupported;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PostProcess2.prototype, "aspectRatio", {
/**
* The aspect ratio of the output texture.
*/
get: function() {
if (this._shareOutputWithPostProcess) {
return this._shareOutputWithPostProcess.aspectRatio;
}
if (this._forcedOutputTexture) {
return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
}
return this.width / this.height;
},
enumerable: true,
configurable: true
});
PostProcess2.prototype.isReady = function() {
return this._effect && this._effect.isReady();
};
PostProcess2.prototype.apply = function() {
if (!this._effect || !this._effect.isReady()) {
return null;
}
this._engine.enableEffect(this._effect);
this._engine.setState(false);
this._engine.setDepthBuffer(false);
this._engine.setDepthWrite(false);
this._engine.setAlphaMode(this.alphaMode);
if (this.alphaConstants) {
this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
}
var source;
if (this._shareOutputWithPostProcess) {
source = this._shareOutputWithPostProcess.inputTexture;
} else if (this._forcedOutputTexture) {
source = this._forcedOutputTexture;
} else {
source = this.inputTexture;
}
this._effect._bindTexture("textureSampler", source);
this._effect.setVector2("scale", this._scaleRatio);
this.onApplyObservable.notifyObservers(this._effect);
return this._effect;
};
PostProcess2.prototype._disposeTextures = function() {
if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
return;
}
if (this._textures.length > 0) {
for (var i2 = 0; i2 < this._textures.length; i2++) {
this._engine._releaseTexture(this._textures.data[i2]);
}
}
this._textures.dispose();
};
PostProcess2.prototype.dispose = function(camera2) {
camera2 = camera2 || this._camera;
this._disposeTextures();
if (this._scene) {
var index_1 = this._scene.postProcesses.indexOf(this);
if (index_1 !== -1) {
this._scene.postProcesses.splice(index_1, 1);
}
} else {
var index_2 = this._engine.postProcesses.indexOf(this);
if (index_2 !== -1) {
this._engine.postProcesses.splice(index_2, 1);
}
}
if (!camera2) {
return;
}
camera2.detachPostProcess(this);
var index = camera2._postProcesses.indexOf(this);
if (index === 0 && camera2._postProcesses.length > 0) {
var firstPostProcess = this._camera._getFirstPostProcess();
if (firstPostProcess) {
firstPostProcess.markTextureDirty();
}
}
this.onActivateObservable.clear();
this.onAfterRenderObservable.clear();
this.onApplyObservable.clear();
this.onBeforeRenderObservable.clear();
this.onSizeChangedObservable.clear();
};
return PostProcess2;
}()
);
BABYLON2.PostProcess = PostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PassPostProcess = (
/** @class */
function(_super) {
__extends(PassPostProcess2, _super);
function PassPostProcess2(name, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (camera2 === void 0) {
camera2 = null;
}
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
return _super.call(this, name, "pass", null, null, options, camera2, samplingMode, engine, reusable, void 0, textureType, void 0, null, blockCompilation) || this;
}
return PassPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.PassPostProcess = PassPostProcess;
})(BABYLON || (BABYLON = {}));
var __assign = function() {
__assign = Object.assign || function(t) {
for (var s, i2 = 1, n = arguments.length; i2 < n; i2++) {
s = arguments[i2];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var BABYLON;
(function(BABYLON2) {
var ShadowGenerator = (
/** @class */
function() {
function ShadowGenerator2(mapSize, light, useFullFloatFirst) {
this._bias = 5e-5;
this._normalBias = 0;
this._blurBoxOffset = 1;
this._blurScale = 2;
this._blurKernel = 1;
this._useKernelBlur = false;
this._filter = ShadowGenerator2.FILTER_NONE;
this._filteringQuality = ShadowGenerator2.QUALITY_HIGH;
this._contactHardeningLightSizeUVRatio = 0.1;
this._darkness = 0;
this._transparencyShadow = false;
this.frustumEdgeFalloff = 0;
this.forceBackFacesOnly = false;
this._lightDirection = BABYLON2.Vector3.Zero();
this._viewMatrix = BABYLON2.Matrix.Zero();
this._projectionMatrix = BABYLON2.Matrix.Zero();
this._transformMatrix = BABYLON2.Matrix.Zero();
this._cachedPosition = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cachedDirection = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._currentFaceIndex = 0;
this._currentFaceIndexCache = 0;
this._defaultTextureMatrix = BABYLON2.Matrix.Identity();
this._mapSize = mapSize;
this._light = light;
this._scene = light.getScene();
light._shadowGenerator = this;
var component = this._scene._getComponent(BABYLON2.SceneComponentConstants.NAME_SHADOWGENERATOR);
if (!component) {
component = new BABYLON2.ShadowGeneratorSceneComponent(this._scene);
this._scene._addComponent(component);
}
var caps = this._scene.getEngine().getCaps();
if (!useFullFloatFirst) {
if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
this._textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
} else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
this._textureType = BABYLON2.Engine.TEXTURETYPE_FLOAT;
} else {
this._textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
} else {
if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
this._textureType = BABYLON2.Engine.TEXTURETYPE_FLOAT;
} else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
this._textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
} else {
this._textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
}
this._initializeGenerator();
this._applyFilterValues();
}
Object.defineProperty(ShadowGenerator2.prototype, "bias", {
/**
* Gets the bias: offset applied on the depth preventing acnea (in light direction).
*/
get: function() {
return this._bias;
},
/**
* Sets the bias: offset applied on the depth preventing acnea (in light direction).
*/
set: function(bias) {
this._bias = bias;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "normalBias", {
/**
* Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
*/
get: function() {
return this._normalBias;
},
/**
* Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
*/
set: function(normalBias) {
this._normalBias = normalBias;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "blurBoxOffset", {
/**
* Gets the blur box offset: offset applied during the blur pass.
* Only usefull if useKernelBlur = false
*/
get: function() {
return this._blurBoxOffset;
},
/**
* Sets the blur box offset: offset applied during the blur pass.
* Only usefull if useKernelBlur = false
*/
set: function(value) {
if (this._blurBoxOffset === value) {
return;
}
this._blurBoxOffset = value;
this._disposeBlurPostProcesses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "blurScale", {
/**
* Gets the blur scale: scale of the blurred texture compared to the main shadow map.
* 2 means half of the size.
*/
get: function() {
return this._blurScale;
},
/**
* Sets the blur scale: scale of the blurred texture compared to the main shadow map.
* 2 means half of the size.
*/
set: function(value) {
if (this._blurScale === value) {
return;
}
this._blurScale = value;
this._disposeBlurPostProcesses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "blurKernel", {
/**
* Gets the blur kernel: kernel size of the blur pass.
* Only usefull if useKernelBlur = true
*/
get: function() {
return this._blurKernel;
},
/**
* Sets the blur kernel: kernel size of the blur pass.
* Only usefull if useKernelBlur = true
*/
set: function(value) {
if (this._blurKernel === value) {
return;
}
this._blurKernel = value;
this._disposeBlurPostProcesses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useKernelBlur", {
/**
* Gets whether the blur pass is a kernel blur (if true) or box blur.
* Only usefull in filtered mode (useBlurExponentialShadowMap...)
*/
get: function() {
return this._useKernelBlur;
},
/**
* Sets whether the blur pass is a kernel blur (if true) or box blur.
* Only usefull in filtered mode (useBlurExponentialShadowMap...)
*/
set: function(value) {
if (this._useKernelBlur === value) {
return;
}
this._useKernelBlur = value;
this._disposeBlurPostProcesses();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "depthScale", {
/**
* Gets the depth scale used in ESM mode.
*/
get: function() {
return this._depthScale !== void 0 ? this._depthScale : this._light.getDepthScale();
},
/**
* Sets the depth scale used in ESM mode.
* This can override the scale stored on the light.
*/
set: function(value) {
this._depthScale = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "filter", {
/**
* Gets the current mode of the shadow generator (normal, PCF, ESM...).
* The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
*/
get: function() {
return this._filter;
},
/**
* Sets the current mode of the shadow generator (normal, PCF, ESM...).
* The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
*/
set: function(value) {
if (this._light.needCube()) {
if (value === ShadowGenerator2.FILTER_BLUREXPONENTIALSHADOWMAP) {
this.useExponentialShadowMap = true;
return;
} else if (value === ShadowGenerator2.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
this.useCloseExponentialShadowMap = true;
return;
} else if (value === ShadowGenerator2.FILTER_PCF || value === ShadowGenerator2.FILTER_PCSS) {
this.usePoissonSampling = true;
return;
}
}
if (value === ShadowGenerator2.FILTER_PCF || value === ShadowGenerator2.FILTER_PCSS) {
if (this._scene.getEngine().webGLVersion === 1) {
this.usePoissonSampling = true;
return;
}
}
if (this._filter === value) {
return;
}
this._filter = value;
this._disposeBlurPostProcesses();
this._applyFilterValues();
this._light._markMeshesAsLightDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "usePoissonSampling", {
/**
* Gets if the current filter is set to Poisson Sampling.
*/
get: function() {
return this.filter === ShadowGenerator2.FILTER_POISSONSAMPLING;
},
/**
* Sets the current filter to Poisson Sampling.
*/
set: function(value) {
if (!value && this.filter !== ShadowGenerator2.FILTER_POISSONSAMPLING) {
return;
}
this.filter = value ? ShadowGenerator2.FILTER_POISSONSAMPLING : ShadowGenerator2.FILTER_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useVarianceShadowMap", {
/**
* Gets if the current filter is set to VSM.
* DEPRECATED. Should use useExponentialShadowMap instead.
*/
get: function() {
BABYLON2.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
return this.useExponentialShadowMap;
},
/**
* Sets the current filter is to VSM.
* DEPRECATED. Should use useExponentialShadowMap instead.
*/
set: function(value) {
BABYLON2.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
this.useExponentialShadowMap = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useBlurVarianceShadowMap", {
/**
* Gets if the current filter is set to blurred VSM.
* DEPRECATED. Should use useBlurExponentialShadowMap instead.
*/
get: function() {
BABYLON2.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
return this.useBlurExponentialShadowMap;
},
/**
* Sets the current filter is to blurred VSM.
* DEPRECATED. Should use useBlurExponentialShadowMap instead.
*/
set: function(value) {
BABYLON2.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
this.useBlurExponentialShadowMap = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useExponentialShadowMap", {
/**
* Gets if the current filter is set to ESM.
*/
get: function() {
return this.filter === ShadowGenerator2.FILTER_EXPONENTIALSHADOWMAP;
},
/**
* Sets the current filter is to ESM.
*/
set: function(value) {
if (!value && this.filter !== ShadowGenerator2.FILTER_EXPONENTIALSHADOWMAP) {
return;
}
this.filter = value ? ShadowGenerator2.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator2.FILTER_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useBlurExponentialShadowMap", {
/**
* Gets if the current filter is set to filtered ESM.
*/
get: function() {
return this.filter === ShadowGenerator2.FILTER_BLUREXPONENTIALSHADOWMAP;
},
/**
* Gets if the current filter is set to filtered ESM.
*/
set: function(value) {
if (!value && this.filter !== ShadowGenerator2.FILTER_BLUREXPONENTIALSHADOWMAP) {
return;
}
this.filter = value ? ShadowGenerator2.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator2.FILTER_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useCloseExponentialShadowMap", {
/**
* Gets if the current filter is set to "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
get: function() {
return this.filter === ShadowGenerator2.FILTER_CLOSEEXPONENTIALSHADOWMAP;
},
/**
* Sets the current filter to "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
set: function(value) {
if (!value && this.filter !== ShadowGenerator2.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
return;
}
this.filter = value ? ShadowGenerator2.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator2.FILTER_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useBlurCloseExponentialShadowMap", {
/**
* Gets if the current filter is set to filtered "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
get: function() {
return this.filter === ShadowGenerator2.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
},
/**
* Sets the current filter to filtered "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
set: function(value) {
if (!value && this.filter !== ShadowGenerator2.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
return;
}
this.filter = value ? ShadowGenerator2.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator2.FILTER_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "usePercentageCloserFiltering", {
/**
* Gets if the current filter is set to "PCF" (percentage closer filtering).
*/
get: function() {
return this.filter === ShadowGenerator2.FILTER_PCF;
},
/**
* Sets the current filter to "PCF" (percentage closer filtering).
*/
set: function(value) {
if (!value && this.filter !== ShadowGenerator2.FILTER_PCF) {
return;
}
this.filter = value ? ShadowGenerator2.FILTER_PCF : ShadowGenerator2.FILTER_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "filteringQuality", {
/**
* Gets the PCF or PCSS Quality.
* Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
*/
get: function() {
return this._filteringQuality;
},
/**
* Sets the PCF or PCSS Quality.
* Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
*/
set: function(filteringQuality) {
this._filteringQuality = filteringQuality;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "useContactHardeningShadow", {
/**
* Gets if the current filter is set to "PCSS" (contact hardening).
*/
get: function() {
return this.filter === ShadowGenerator2.FILTER_PCSS;
},
/**
* Sets the current filter to "PCSS" (contact hardening).
*/
set: function(value) {
if (!value && this.filter !== ShadowGenerator2.FILTER_PCSS) {
return;
}
this.filter = value ? ShadowGenerator2.FILTER_PCSS : ShadowGenerator2.FILTER_NONE;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ShadowGenerator2.prototype, "contactHardeningLightSizeUVRatio", {
/**
* Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
* Using a ratio helps keeping shape stability independently of the map size.
*
* It does not account for the light projection as it was having too much
* instability during the light setup or during light position changes.
*
* Only valid if useContactHardeningShadow is true.
*/
get: function() {
return this._contactHardeningLightSizeUVRatio;
},
/**
* Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
* Using a ratio helps keeping shape stability independently of the map size.
*
* It does not account for the light projection as it was having too much
* instability during the light setup or during light position changes.
*
* Only valid if useContactHardeningShadow is true.
*/
set: function(contactHardeningLightSizeUVRatio) {
this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
},
enumerable: true,
configurable: true
});
ShadowGenerator2.prototype.getDarkness = function() {
return this._darkness;
};
ShadowGenerator2.prototype.setDarkness = function(darkness) {
if (darkness >= 1) {
this._darkness = 1;
} else if (darkness <= 0) {
this._darkness = 0;
} else {
this._darkness = darkness;
}
return this;
};
ShadowGenerator2.prototype.setTransparencyShadow = function(transparent) {
this._transparencyShadow = transparent;
return this;
};
ShadowGenerator2.prototype.getShadowMap = function() {
return this._shadowMap;
};
ShadowGenerator2.prototype.getShadowMapForRendering = function() {
if (this._shadowMap2) {
return this._shadowMap2;
}
return this._shadowMap;
};
ShadowGenerator2.prototype.addShadowCaster = function(mesh2, includeDescendants) {
if (includeDescendants === void 0) {
includeDescendants = true;
}
var _a;
if (!this._shadowMap) {
return this;
}
if (!this._shadowMap.renderList) {
this._shadowMap.renderList = [];
}
this._shadowMap.renderList.push(mesh2);
if (includeDescendants) {
(_a = this._shadowMap.renderList).push.apply(_a, mesh2.getChildMeshes());
}
return this;
};
ShadowGenerator2.prototype.removeShadowCaster = function(mesh2, includeDescendants) {
if (includeDescendants === void 0) {
includeDescendants = true;
}
if (!this._shadowMap || !this._shadowMap.renderList) {
return this;
}
var index = this._shadowMap.renderList.indexOf(mesh2);
if (index !== -1) {
this._shadowMap.renderList.splice(index, 1);
}
if (includeDescendants) {
for (var _i = 0, _a = mesh2.getChildren(); _i < _a.length; _i++) {
var child = _a[_i];
this.removeShadowCaster(child);
}
}
return this;
};
ShadowGenerator2.prototype.getLight = function() {
return this._light;
};
ShadowGenerator2.prototype._initializeGenerator = function() {
this._light._markMeshesAsLightDirty();
this._initializeShadowMap();
};
ShadowGenerator2.prototype._initializeShadowMap = function() {
var _this = this;
var engine = this._scene.getEngine();
if (engine.webGLVersion > 1) {
this._shadowMap = new BABYLON2.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), void 0, false, false);
this._shadowMap.createDepthStencilTexture(BABYLON2.Engine.LESS, true);
} else {
this._shadowMap = new BABYLON2.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
}
this._shadowMap.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._shadowMap.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._shadowMap.anisotropicFilteringLevel = 1;
this._shadowMap.updateSamplingMode(BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
this._shadowMap.renderParticles = false;
this._shadowMap.ignoreCameraViewport = true;
this._shadowMap.onBeforeRenderObservable.add(function(faceIndex) {
_this._currentFaceIndex = faceIndex;
if (_this._filter === ShadowGenerator2.FILTER_PCF) {
engine.setColorWrite(false);
}
});
this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
this._shadowMap.onAfterUnbindObservable.add(function() {
if (_this._filter === ShadowGenerator2.FILTER_PCF) {
engine.setColorWrite(true);
}
if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
return;
}
var shadowMap = _this.getShadowMapForRendering();
if (shadowMap) {
_this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
}
});
var clearZero = new BABYLON2.Color4(0, 0, 0, 0);
var clearOne = new BABYLON2.Color4(1, 1, 1, 1);
this._shadowMap.onClearObservable.add(function(engine2) {
if (_this._filter === ShadowGenerator2.FILTER_PCF) {
engine2.clear(clearOne, false, true, false);
} else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
engine2.clear(clearZero, true, true, false);
} else {
engine2.clear(clearOne, true, true, false);
}
});
};
ShadowGenerator2.prototype._initializeBlurRTTAndPostProcesses = function() {
var _this = this;
var engine = this._scene.getEngine();
var targetSize = this._mapSize / this.blurScale;
if (!this.useKernelBlur || this.blurScale !== 1) {
this._shadowMap2 = new BABYLON2.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
this._shadowMap2.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._shadowMap2.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._shadowMap2.updateSamplingMode(BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
}
if (this.useKernelBlur) {
this._kernelBlurXPostprocess = new BABYLON2.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON2.Vector2(1, 0), this.blurKernel, 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
this._kernelBlurXPostprocess.width = targetSize;
this._kernelBlurXPostprocess.height = targetSize;
this._kernelBlurXPostprocess.onApplyObservable.add(function(effect) {
effect.setTexture("textureSampler", _this._shadowMap);
});
this._kernelBlurYPostprocess = new BABYLON2.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON2.Vector2(0, 1), this.blurKernel, 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
this._kernelBlurXPostprocess.autoClear = false;
this._kernelBlurYPostprocess.autoClear = false;
if (this._textureType === BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT) {
this._kernelBlurXPostprocess.packedFloat = true;
this._kernelBlurYPostprocess.packedFloat = true;
}
this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
} else {
this._boxBlurPostprocess = new BABYLON2.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
this._boxBlurPostprocess.onApplyObservable.add(function(effect) {
effect.setFloat2("screenSize", targetSize, targetSize);
effect.setTexture("textureSampler", _this._shadowMap);
});
this._boxBlurPostprocess.autoClear = false;
this._blurPostProcesses = [this._boxBlurPostprocess];
}
};
ShadowGenerator2.prototype._renderForShadowMap = function(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
var index;
var engine = this._scene.getEngine();
if (depthOnlySubMeshes.length) {
engine.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
}
engine.setColorWrite(true);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
}
if (this._transparencyShadow) {
for (index = 0; index < transparentSubMeshes.length; index++) {
this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
}
}
};
ShadowGenerator2.prototype._renderSubMeshForShadowMap = function(subMesh) {
var _this = this;
var mesh2 = subMesh.getRenderingMesh();
var scene = this._scene;
var engine = scene.getEngine();
var material = subMesh.getMaterial();
if (!material) {
return;
}
engine.setState(material.backFaceCulling);
var batch = mesh2._getInstancesRenderList(subMesh._id);
if (batch.mustReturn) {
return;
}
var hardwareInstancedRendering = engine.getCaps().instancedArrays && batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0;
if (this.isReady(subMesh, hardwareInstancedRendering)) {
engine.enableEffect(this._effect);
mesh2._bind(subMesh, this._effect, BABYLON2.Material.TriangleFillMode);
this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
this._effect.setMatrix("viewProjection", this.getTransformMatrix());
if (this.getLight().getTypeID() === BABYLON2.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
this._effect.setVector3("lightData", this._cachedDirection);
} else {
this._effect.setVector3("lightData", this._cachedPosition);
}
if (scene.activeCamera) {
this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
}
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
this._effect.setTexture("diffuseSampler", alphaTexture);
this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders) {
this._effect.setMatrices("mBones", mesh2.skeleton.getTransformMatrices(mesh2));
}
BABYLON2.MaterialHelper.BindMorphTargetParameters(mesh2, this._effect);
if (this.forceBackFacesOnly) {
engine.setState(true, 0, false, true);
}
mesh2._processRendering(subMesh, this._effect, BABYLON2.Material.TriangleFillMode, batch, hardwareInstancedRendering, function(isInstance, world) {
return _this._effect.setMatrix("world", world);
});
if (this.forceBackFacesOnly) {
engine.setState(true, 0, false, false);
}
} else {
if (this._shadowMap) {
this._shadowMap.resetRefreshCounter();
}
}
};
ShadowGenerator2.prototype._applyFilterValues = function() {
if (!this._shadowMap) {
return;
}
if (this.filter === ShadowGenerator2.FILTER_NONE || this.filter === ShadowGenerator2.FILTER_PCSS) {
this._shadowMap.updateSamplingMode(BABYLON2.Texture.NEAREST_SAMPLINGMODE);
} else {
this._shadowMap.updateSamplingMode(BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
}
};
ShadowGenerator2.prototype.forceCompilation = function(onCompiled, options) {
var _this = this;
var localOptions = __assign({ useInstances: false }, options);
var shadowMap = this.getShadowMap();
if (!shadowMap) {
if (onCompiled) {
onCompiled(this);
}
return;
}
var renderList = shadowMap.renderList;
if (!renderList) {
if (onCompiled) {
onCompiled(this);
}
return;
}
var subMeshes = new Array();
for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
var mesh2 = renderList_1[_i];
subMeshes.push.apply(subMeshes, mesh2.subMeshes);
}
if (subMeshes.length === 0) {
if (onCompiled) {
onCompiled(this);
}
return;
}
var currentIndex = 0;
var checkReady = function() {
if (!_this._scene || !_this._scene.getEngine()) {
return;
}
while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
currentIndex++;
if (currentIndex >= subMeshes.length) {
if (onCompiled) {
onCompiled(_this);
}
return;
}
}
setTimeout(checkReady, 16);
};
checkReady();
};
ShadowGenerator2.prototype.forceCompilationAsync = function(options) {
var _this = this;
return new Promise(function(resolve) {
_this.forceCompilation(function() {
resolve();
}, options);
});
};
ShadowGenerator2.prototype.isReady = function(subMesh, useInstances) {
var defines = [];
if (this._textureType !== BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT) {
defines.push("#define FLOAT");
}
if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
defines.push("#define ESM");
} else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
defines.push("#define DEPTHTEXTURE");
}
var attribs = [BABYLON2.VertexBuffer.PositionKind];
var mesh2 = subMesh.getMesh();
var material = subMesh.getMaterial();
if (this.normalBias && mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
attribs.push(BABYLON2.VertexBuffer.NormalKind);
defines.push("#define NORMAL");
if (mesh2.nonUniformScaling) {
defines.push("#define NONUNIFORMSCALING");
}
if (this.getLight().getTypeID() === BABYLON2.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
defines.push("#define DIRECTIONINLIGHTDATA");
}
}
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
defines.push("#define ALPHATEST");
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
defines.push("#define UV1");
}
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind)) {
if (alphaTexture.coordinatesIndex === 1) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
defines.push("#define UV2");
}
}
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (mesh2.numBoneInfluencers > 4) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
defines.push("#define BonesPerMesh " + (mesh2.skeleton.bones.length + 1));
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
var manager = mesh2.morphTargetManager;
var morphInfluencers = 0;
if (manager) {
if (manager.numInfluencers > 0) {
defines.push("#define MORPHTARGETS");
morphInfluencers = manager.numInfluencers;
defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
BABYLON2.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh2, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
}
}
if (useInstances) {
defines.push("#define INSTANCES");
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, void 0, void 0, void 0, { maxSimultaneousMorphTargets: morphInfluencers });
}
if (!this._effect.isReady()) {
return false;
}
if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
this._initializeBlurRTTAndPostProcesses();
}
}
if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
return false;
}
if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
return false;
}
if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
return false;
}
return true;
};
ShadowGenerator2.prototype.prepareDefines = function(defines, lightIndex) {
var scene = this._scene;
var light = this._light;
if (!scene.shadowsEnabled || !light.shadowEnabled) {
return;
}
defines["SHADOW" + lightIndex] = true;
if (this.useContactHardeningShadow) {
defines["SHADOWPCSS" + lightIndex] = true;
if (this._filteringQuality === ShadowGenerator2.QUALITY_LOW) {
defines["SHADOWLOWQUALITY" + lightIndex] = true;
} else if (this._filteringQuality === ShadowGenerator2.QUALITY_MEDIUM) {
defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
}
}
if (this.usePercentageCloserFiltering) {
defines["SHADOWPCF" + lightIndex] = true;
if (this._filteringQuality === ShadowGenerator2.QUALITY_LOW) {
defines["SHADOWLOWQUALITY" + lightIndex] = true;
} else if (this._filteringQuality === ShadowGenerator2.QUALITY_MEDIUM) {
defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
}
} else if (this.usePoissonSampling) {
defines["SHADOWPOISSON" + lightIndex] = true;
} else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
defines["SHADOWESM" + lightIndex] = true;
} else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
defines["SHADOWCLOSEESM" + lightIndex] = true;
}
if (light.needCube()) {
defines["SHADOWCUBE" + lightIndex] = true;
}
};
ShadowGenerator2.prototype.bindShadowLight = function(lightIndex, effect) {
var light = this._light;
var scene = this._scene;
if (!scene.shadowsEnabled || !light.shadowEnabled) {
return;
}
var camera2 = scene.activeCamera;
if (!camera2) {
return;
}
var shadowMap = this.getShadowMap();
if (!shadowMap) {
return;
}
if (!light.needCube()) {
effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
}
if (this._filter === ShadowGenerator2.FILTER_PCF) {
effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
} else if (this._filter === ShadowGenerator2.FILTER_PCSS) {
effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
} else {
effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
}
light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera2), this.getLight().getDepthMinZ(camera2) + this.getLight().getDepthMaxZ(camera2), lightIndex);
};
ShadowGenerator2.prototype.getTransformMatrix = function() {
var scene = this._scene;
if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
return this._transformMatrix;
}
this._currentRenderID = scene.getRenderId();
this._currentFaceIndexCache = this._currentFaceIndex;
var lightPosition = this._light.position;
if (this._light.computeTransformedInformation()) {
lightPosition = this._light.transformedPosition;
}
BABYLON2.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
if (Math.abs(BABYLON2.Vector3.Dot(this._lightDirection, BABYLON2.Vector3.Up())) === 1) {
this._lightDirection.z = 1e-13;
}
if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
this._cachedPosition.copyFrom(lightPosition);
this._cachedDirection.copyFrom(this._lightDirection);
BABYLON2.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON2.Vector3.Up(), this._viewMatrix);
var shadowMap = this.getShadowMap();
if (shadowMap) {
var renderList = shadowMap.renderList;
if (renderList) {
this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
}
}
this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
}
return this._transformMatrix;
};
ShadowGenerator2.prototype.recreateShadowMap = function() {
var shadowMap = this._shadowMap;
if (!shadowMap) {
return;
}
var renderList = shadowMap.renderList;
this._disposeRTTandPostProcesses();
this._initializeGenerator();
this.filter = this.filter;
this._applyFilterValues();
this._shadowMap.renderList = renderList;
};
ShadowGenerator2.prototype._disposeBlurPostProcesses = function() {
if (this._shadowMap2) {
this._shadowMap2.dispose();
this._shadowMap2 = null;
}
if (this._boxBlurPostprocess) {
this._boxBlurPostprocess.dispose();
this._boxBlurPostprocess = null;
}
if (this._kernelBlurXPostprocess) {
this._kernelBlurXPostprocess.dispose();
this._kernelBlurXPostprocess = null;
}
if (this._kernelBlurYPostprocess) {
this._kernelBlurYPostprocess.dispose();
this._kernelBlurYPostprocess = null;
}
this._blurPostProcesses = [];
};
ShadowGenerator2.prototype._disposeRTTandPostProcesses = function() {
if (this._shadowMap) {
this._shadowMap.dispose();
this._shadowMap = null;
}
this._disposeBlurPostProcesses();
};
ShadowGenerator2.prototype.dispose = function() {
this._disposeRTTandPostProcesses();
if (this._light) {
this._light._shadowGenerator = null;
this._light._markMeshesAsLightDirty();
}
};
ShadowGenerator2.prototype.serialize = function() {
var serializationObject = {};
var shadowMap = this.getShadowMap();
if (!shadowMap) {
return serializationObject;
}
serializationObject.lightId = this._light.id;
serializationObject.mapSize = shadowMap.getRenderSize();
serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
serializationObject.usePoissonSampling = this.usePoissonSampling;
serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
serializationObject.depthScale = this.depthScale;
serializationObject.darkness = this.getDarkness();
serializationObject.blurBoxOffset = this.blurBoxOffset;
serializationObject.blurKernel = this.blurKernel;
serializationObject.blurScale = this.blurScale;
serializationObject.useKernelBlur = this.useKernelBlur;
serializationObject.transparencyShadow = this._transparencyShadow;
serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
serializationObject.bias = this.bias;
serializationObject.normalBias = this.normalBias;
serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
serializationObject.filteringQuality = this.filteringQuality;
serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
serializationObject.renderList = [];
if (shadowMap.renderList) {
for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
var mesh2 = shadowMap.renderList[meshIndex];
serializationObject.renderList.push(mesh2.id);
}
}
return serializationObject;
};
ShadowGenerator2.Parse = function(parsedShadowGenerator, scene) {
var light = scene.getLightByID(parsedShadowGenerator.lightId);
var shadowGenerator = new ShadowGenerator2(parsedShadowGenerator.mapSize, light);
var shadowMap = shadowGenerator.getShadowMap();
for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
meshes.forEach(function(mesh2) {
if (!shadowMap) {
return;
}
if (!shadowMap.renderList) {
shadowMap.renderList = [];
}
shadowMap.renderList.push(mesh2);
});
}
if (parsedShadowGenerator.usePoissonSampling) {
shadowGenerator.usePoissonSampling = true;
} else if (parsedShadowGenerator.useExponentialShadowMap) {
shadowGenerator.useExponentialShadowMap = true;
} else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
shadowGenerator.useBlurExponentialShadowMap = true;
} else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
shadowGenerator.useCloseExponentialShadowMap = true;
} else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
shadowGenerator.useBlurCloseExponentialShadowMap = true;
} else if (parsedShadowGenerator.usePercentageCloserFiltering) {
shadowGenerator.usePercentageCloserFiltering = true;
} else if (parsedShadowGenerator.useContactHardeningShadow) {
shadowGenerator.useContactHardeningShadow = true;
}
if (parsedShadowGenerator.filteringQuality) {
shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
}
if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
} else if (parsedShadowGenerator.useVarianceShadowMap) {
shadowGenerator.useExponentialShadowMap = true;
} else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
shadowGenerator.useBlurExponentialShadowMap = true;
}
if (parsedShadowGenerator.depthScale) {
shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
}
if (parsedShadowGenerator.blurScale) {
shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
}
if (parsedShadowGenerator.blurBoxOffset) {
shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
}
if (parsedShadowGenerator.useKernelBlur) {
shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
}
if (parsedShadowGenerator.blurKernel) {
shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
}
if (parsedShadowGenerator.bias !== void 0) {
shadowGenerator.bias = parsedShadowGenerator.bias;
}
if (parsedShadowGenerator.normalBias !== void 0) {
shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
}
if (parsedShadowGenerator.frustumEdgeFalloff !== void 0) {
shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
}
if (parsedShadowGenerator.darkness) {
shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
}
if (parsedShadowGenerator.transparencyShadow) {
shadowGenerator.setTransparencyShadow(true);
}
shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
return shadowGenerator;
};
ShadowGenerator2.FILTER_NONE = 0;
ShadowGenerator2.FILTER_EXPONENTIALSHADOWMAP = 1;
ShadowGenerator2.FILTER_POISSONSAMPLING = 2;
ShadowGenerator2.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
ShadowGenerator2.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
ShadowGenerator2.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
ShadowGenerator2.FILTER_PCF = 6;
ShadowGenerator2.FILTER_PCSS = 7;
ShadowGenerator2.QUALITY_HIGH = 0;
ShadowGenerator2.QUALITY_MEDIUM = 1;
ShadowGenerator2.QUALITY_LOW = 2;
return ShadowGenerator2;
}()
);
BABYLON2.ShadowGenerator = ShadowGenerator;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractScene.AddParser(BABYLON2.SceneComponentConstants.NAME_SHADOWGENERATOR, function(parsedData, scene, container, rootUrl) {
if (parsedData.shadowGenerators !== void 0 && parsedData.shadowGenerators !== null) {
for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
var parsedShadowGenerator = parsedData.shadowGenerators[index];
BABYLON2.ShadowGenerator.Parse(parsedShadowGenerator, scene);
}
}
});
var ShadowGeneratorSceneComponent = (
/** @class */
function() {
function ShadowGeneratorSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_SHADOWGENERATOR;
this.scene = scene;
}
ShadowGeneratorSceneComponent2.prototype.register = function() {
this.scene._gatherRenderTargetsStage.registerStep(BABYLON2.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
};
ShadowGeneratorSceneComponent2.prototype.rebuild = function() {
};
ShadowGeneratorSceneComponent2.prototype.serialize = function(serializationObject) {
serializationObject.shadowGenerators = [];
var lights = this.scene.lights;
for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
var light = lights_1[_i];
var shadowGenerator = light.getShadowGenerator();
if (shadowGenerator) {
serializationObject.shadowGenerators.push(shadowGenerator.serialize());
}
}
};
ShadowGeneratorSceneComponent2.prototype.addFromContainer = function(container) {
};
ShadowGeneratorSceneComponent2.prototype.removeFromContainer = function(container) {
};
ShadowGeneratorSceneComponent2.prototype.dispose = function() {
};
ShadowGeneratorSceneComponent2.prototype._gatherRenderTargets = function(renderTargets) {
var scene = this.scene;
if (this.scene.shadowsEnabled) {
for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
var light = scene.lights[lightIndex];
var shadowGenerator = light.getShadowGenerator();
if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
var shadowMap = shadowGenerator.getShadowMap();
if (scene.textures.indexOf(shadowMap) !== -1) {
renderTargets.push(shadowMap);
}
}
}
}
};
return ShadowGeneratorSceneComponent2;
}()
);
BABYLON2.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DefaultLoadingScreen = (
/** @class */
function() {
function DefaultLoadingScreen2(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
if (_loadingText === void 0) {
_loadingText = "";
}
if (_loadingDivBackgroundColor === void 0) {
_loadingDivBackgroundColor = "black";
}
var _this = this;
this._renderingCanvas = _renderingCanvas;
this._loadingText = _loadingText;
this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
this._resizeLoadingUI = function() {
var canvasRect = _this._renderingCanvas.getBoundingClientRect();
var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
if (!_this._loadingDiv) {
return;
}
_this._loadingDiv.style.position = canvasPositioning === "fixed" ? "fixed" : "absolute";
_this._loadingDiv.style.left = canvasRect.left + "px";
_this._loadingDiv.style.top = canvasRect.top + "px";
_this._loadingDiv.style.width = canvasRect.width + "px";
_this._loadingDiv.style.height = canvasRect.height + "px";
};
}
DefaultLoadingScreen2.prototype.displayLoadingUI = function() {
if (this._loadingDiv) {
return;
}
this._loadingDiv = document.createElement("div");
this._loadingDiv.id = "babylonjsLoadingDiv";
this._loadingDiv.style.opacity = "0";
this._loadingDiv.style.transition = "opacity 1.5s ease";
this._loadingDiv.style.pointerEvents = "none";
this._loadingTextDiv = document.createElement("div");
this._loadingTextDiv.style.position = "absolute";
this._loadingTextDiv.style.left = "0";
this._loadingTextDiv.style.top = "50%";
this._loadingTextDiv.style.marginTop = "80px";
this._loadingTextDiv.style.width = "100%";
this._loadingTextDiv.style.height = "20px";
this._loadingTextDiv.style.fontFamily = "Arial";
this._loadingTextDiv.style.fontSize = "14px";
this._loadingTextDiv.style.color = "white";
this._loadingTextDiv.style.textAlign = "center";
this._loadingTextDiv.innerHTML = "Loading";
this._loadingDiv.appendChild(this._loadingTextDiv);
this._loadingTextDiv.innerHTML = this._loadingText;
var style = document.createElement("style");
style.type = "text/css";
var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
style.innerHTML = keyFrames;
document.getElementsByTagName("head")[0].appendChild(style);
var imgBack = new Image();
imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
imgBack.style.position = "absolute";
imgBack.style.left = "50%";
imgBack.style.top = "50%";
imgBack.style.marginLeft = "-60px";
imgBack.style.marginTop = "-60px";
imgBack.style.animation = "spin1 2s infinite ease-in-out";
imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
imgBack.style.transformOrigin = "50% 50%";
imgBack.style.webkitTransformOrigin = "50% 50%";
this._loadingDiv.appendChild(imgBack);
this._resizeLoadingUI();
window.addEventListener("resize", this._resizeLoadingUI);
this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
document.body.appendChild(this._loadingDiv);
this._loadingDiv.style.opacity = "1";
};
DefaultLoadingScreen2.prototype.hideLoadingUI = function() {
var _this = this;
if (!this._loadingDiv) {
return;
}
var onTransitionEnd = function() {
if (!_this._loadingDiv) {
return;
}
document.body.removeChild(_this._loadingDiv);
window.removeEventListener("resize", _this._resizeLoadingUI);
_this._loadingDiv = null;
};
this._loadingDiv.style.opacity = "0";
this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
};
Object.defineProperty(DefaultLoadingScreen2.prototype, "loadingUIText", {
get: function() {
return this._loadingText;
},
/**
* Gets or sets the text to display while loading
*/
set: function(text) {
this._loadingText = text;
if (this._loadingTextDiv) {
this._loadingTextDiv.innerHTML = this._loadingText;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultLoadingScreen2.prototype, "loadingUIBackgroundColor", {
/**
* Gets or sets the color to use for the background
*/
get: function() {
return this._loadingDivBackgroundColor;
},
set: function(color) {
this._loadingDivBackgroundColor = color;
if (!this._loadingDiv) {
return;
}
this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
},
enumerable: true,
configurable: true
});
return DefaultLoadingScreen2;
}()
);
BABYLON2.DefaultLoadingScreen = DefaultLoadingScreen;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SceneLoaderProgressEvent = (
/** @class */
function() {
function SceneLoaderProgressEvent2(lengthComputable, loaded, total) {
this.lengthComputable = lengthComputable;
this.loaded = loaded;
this.total = total;
}
SceneLoaderProgressEvent2.FromProgressEvent = function(event) {
return new SceneLoaderProgressEvent2(event.lengthComputable, event.loaded, event.total);
};
return SceneLoaderProgressEvent2;
}()
);
BABYLON2.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
var SceneLoader = (
/** @class */
function() {
function SceneLoader2() {
}
Object.defineProperty(SceneLoader2, "ForceFullSceneLoadingForIncremental", {
/**
* Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
*/
get: function() {
return SceneLoader2._ForceFullSceneLoadingForIncremental;
},
set: function(value) {
SceneLoader2._ForceFullSceneLoadingForIncremental = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneLoader2, "ShowLoadingScreen", {
/**
* Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
*/
get: function() {
return SceneLoader2._ShowLoadingScreen;
},
set: function(value) {
SceneLoader2._ShowLoadingScreen = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneLoader2, "loggingLevel", {
/**
* Defines the current logging level (while loading the scene)
* @ignorenaming
*/
get: function() {
return SceneLoader2._loggingLevel;
},
set: function(value) {
SceneLoader2._loggingLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneLoader2, "CleanBoneMatrixWeights", {
/**
* Gets or set a boolean indicating if matrix weights must be cleaned upon loading
*/
get: function() {
return SceneLoader2._CleanBoneMatrixWeights;
},
set: function(value) {
SceneLoader2._CleanBoneMatrixWeights = value;
},
enumerable: true,
configurable: true
});
SceneLoader2._getDefaultPlugin = function() {
return SceneLoader2._registeredPlugins[".babylon"];
};
SceneLoader2._getPluginForExtension = function(extension) {
var registeredPlugin = SceneLoader2._registeredPlugins[extension];
if (registeredPlugin) {
return registeredPlugin;
}
BABYLON2.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
return SceneLoader2._getDefaultPlugin();
};
SceneLoader2._getPluginForDirectLoad = function(data2) {
for (var extension in SceneLoader2._registeredPlugins) {
var plugin = SceneLoader2._registeredPlugins[extension].plugin;
if (plugin.canDirectLoad && plugin.canDirectLoad(data2)) {
return SceneLoader2._registeredPlugins[extension];
}
}
return SceneLoader2._getDefaultPlugin();
};
SceneLoader2._getPluginForFilename = function(sceneFilename) {
var queryStringPosition = sceneFilename.indexOf("?");
if (queryStringPosition !== -1) {
sceneFilename = sceneFilename.substring(0, queryStringPosition);
}
var dotPosition = sceneFilename.lastIndexOf(".");
var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
return SceneLoader2._getPluginForExtension(extension);
};
SceneLoader2._getDirectLoad = function(sceneFilename) {
if (sceneFilename.substr(0, 5) === "data:") {
return sceneFilename.substr(5);
}
return null;
};
SceneLoader2._loadData = function(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
var directLoad = SceneLoader2._getDirectLoad(fileInfo.name);
var registeredPlugin = pluginExtension ? SceneLoader2._getPluginForExtension(pluginExtension) : directLoad ? SceneLoader2._getPluginForDirectLoad(fileInfo.name) : SceneLoader2._getPluginForFilename(fileInfo.name);
var plugin;
if (registeredPlugin.plugin.createPlugin) {
plugin = registeredPlugin.plugin.createPlugin();
} else {
plugin = registeredPlugin.plugin;
}
var useArrayBuffer = registeredPlugin.isBinary;
var database;
SceneLoader2.OnPluginActivatedObservable.notifyObservers(plugin);
var dataCallback = function(data2, responseURL) {
if (scene.isDisposed) {
onError("Scene has been disposed");
return;
}
scene.database = database;
onSuccess(plugin, data2, responseURL);
};
var request = null;
var pluginDisposed = false;
var onDisposeObservable = plugin.onDisposeObservable;
if (onDisposeObservable) {
onDisposeObservable.add(function() {
pluginDisposed = true;
if (request) {
request.abort();
request = null;
}
onDispose();
});
}
var manifestChecked = function() {
if (pluginDisposed) {
return;
}
request = BABYLON2.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function(event) {
onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
} : void 0, database, useArrayBuffer, function(request2, exception) {
onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
});
};
if (directLoad) {
dataCallback(directLoad);
return plugin;
}
if (fileInfo.rootUrl.indexOf("file:") === -1) {
var engine = scene.getEngine();
var canUseOfflineSupport = engine.enableOfflineSupport;
if (canUseOfflineSupport) {
var exceptionFound = false;
for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
var regex = _a[_i];
if (regex.test(fileInfo.url)) {
exceptionFound = true;
break;
}
}
canUseOfflineSupport = !exceptionFound;
}
if (canUseOfflineSupport) {
database = new BABYLON2.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
} else {
manifestChecked();
}
} else {
var file = BABYLON2.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
if (file) {
request = BABYLON2.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
} else {
onError("Unable to find file named " + fileInfo.name);
}
}
return plugin;
};
SceneLoader2._getFileInfo = function(rootUrl, sceneFilename) {
var url;
var name;
if (!sceneFilename) {
url = rootUrl;
name = BABYLON2.Tools.GetFilename(rootUrl);
rootUrl = BABYLON2.Tools.GetFolderPath(rootUrl);
} else {
if (sceneFilename.substr(0, 1) === "/") {
BABYLON2.Tools.Error("Wrong sceneFilename parameter");
return null;
}
url = rootUrl + sceneFilename;
name = sceneFilename;
}
return {
url,
rootUrl,
name
};
};
SceneLoader2.GetPluginForExtension = function(extension) {
return SceneLoader2._getPluginForExtension(extension).plugin;
};
SceneLoader2.IsPluginForExtensionAvailable = function(extension) {
return !!SceneLoader2._registeredPlugins[extension];
};
SceneLoader2.RegisterPlugin = function(plugin) {
if (typeof plugin.extensions === "string") {
var extension = plugin.extensions;
SceneLoader2._registeredPlugins[extension.toLowerCase()] = {
plugin,
isBinary: false
};
} else {
var extensions = plugin.extensions;
Object.keys(extensions).forEach(function(extension2) {
SceneLoader2._registeredPlugins[extension2.toLowerCase()] = {
plugin,
isBinary: extensions[extension2].isBinary
};
});
}
};
SceneLoader2.ImportMesh = function(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) {
sceneFilename = "";
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
if (onSuccess === void 0) {
onSuccess = null;
}
if (onProgress === void 0) {
onProgress = null;
}
if (onError === void 0) {
onError = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
if (!scene) {
BABYLON2.Tools.Error("No scene available to import mesh to");
return null;
}
var fileInfo = SceneLoader2._getFileInfo(rootUrl, sceneFilename);
if (!fileInfo) {
return null;
}
var loadingToken = {};
scene._addPendingData(loadingToken);
var disposeHandler = function() {
scene._removePendingData(loadingToken);
};
var errorHandler = function(message, exception) {
var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
if (onError) {
onError(scene, errorMessage, exception);
} else {
BABYLON2.Tools.Error(errorMessage);
}
disposeHandler();
};
var progressHandler = onProgress ? function(event) {
try {
onProgress(event);
} catch (e2) {
errorHandler("Error in onProgress callback", e2);
}
} : void 0;
var successHandler = function(meshes, particleSystems, skeletons, animationGroups) {
scene.importedMeshesFiles.push(fileInfo.url);
if (onSuccess) {
try {
onSuccess(meshes, particleSystems, skeletons, animationGroups);
} catch (e2) {
errorHandler("Error in onSuccess callback", e2);
}
}
scene._removePendingData(loadingToken);
};
return SceneLoader2._loadData(fileInfo, scene, function(plugin, data2, responseURL) {
if (plugin.rewriteRootURL) {
fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
}
if (plugin.importMesh) {
var syncedPlugin = plugin;
var meshes = new Array();
var particleSystems = new Array();
var skeletons = new Array();
if (!syncedPlugin.importMesh(meshNames, scene, data2, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
return;
}
scene.loadingPluginName = plugin.name;
successHandler(meshes, particleSystems, skeletons, []);
} else {
var asyncedPlugin = plugin;
asyncedPlugin.importMeshAsync(meshNames, scene, data2, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function(result) {
scene.loadingPluginName = plugin.name;
successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
}).catch(function(error) {
errorHandler(error.message, error);
});
}
}, progressHandler, errorHandler, disposeHandler, pluginExtension);
};
SceneLoader2.ImportMeshAsync = function(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
if (sceneFilename === void 0) {
sceneFilename = "";
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
if (onProgress === void 0) {
onProgress = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
return new Promise(function(resolve, reject) {
SceneLoader2.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function(meshes, particleSystems, skeletons, animationGroups) {
resolve({
meshes,
particleSystems,
skeletons,
animationGroups
});
}, onProgress, function(scene2, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
SceneLoader2.Load = function(rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
if (onSuccess === void 0) {
onSuccess = null;
}
if (onProgress === void 0) {
onProgress = null;
}
if (onError === void 0) {
onError = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
return SceneLoader2.Append(rootUrl, sceneFilename, new BABYLON2.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
};
SceneLoader2.LoadAsync = function(rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
if (onProgress === void 0) {
onProgress = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
return new Promise(function(resolve, reject) {
SceneLoader2.Load(rootUrl, sceneFilename, engine, function(scene) {
resolve(scene);
}, onProgress, function(scene, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
SceneLoader2.Append = function(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) {
sceneFilename = "";
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
if (onSuccess === void 0) {
onSuccess = null;
}
if (onProgress === void 0) {
onProgress = null;
}
if (onError === void 0) {
onError = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
if (!scene) {
BABYLON2.Tools.Error("No scene available to append to");
return null;
}
var fileInfo = SceneLoader2._getFileInfo(rootUrl, sceneFilename);
if (!fileInfo) {
return null;
}
if (SceneLoader2.ShowLoadingScreen) {
scene.getEngine().displayLoadingUI();
}
var loadingToken = {};
scene._addPendingData(loadingToken);
var disposeHandler = function() {
scene._removePendingData(loadingToken);
scene.getEngine().hideLoadingUI();
};
var errorHandler = function(message, exception) {
var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
if (onError) {
onError(scene, errorMessage, exception);
} else {
BABYLON2.Tools.Error(errorMessage);
}
disposeHandler();
};
var progressHandler = onProgress ? function(event) {
try {
onProgress(event);
} catch (e2) {
errorHandler("Error in onProgress callback", e2);
}
} : void 0;
var successHandler = function() {
if (onSuccess) {
try {
onSuccess(scene);
} catch (e2) {
errorHandler("Error in onSuccess callback", e2);
}
}
scene._removePendingData(loadingToken);
};
return SceneLoader2._loadData(fileInfo, scene, function(plugin, data2, responseURL) {
if (plugin.load) {
var syncedPlugin = plugin;
if (!syncedPlugin.load(scene, data2, fileInfo.rootUrl, errorHandler)) {
return;
}
scene.loadingPluginName = plugin.name;
successHandler();
} else {
var asyncedPlugin = plugin;
asyncedPlugin.loadAsync(scene, data2, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function() {
scene.loadingPluginName = plugin.name;
successHandler();
}).catch(function(error) {
errorHandler(error.message, error);
});
}
if (SceneLoader2.ShowLoadingScreen) {
scene.executeWhenReady(function() {
scene.getEngine().hideLoadingUI();
});
}
}, progressHandler, errorHandler, disposeHandler, pluginExtension);
};
SceneLoader2.AppendAsync = function(rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
if (sceneFilename === void 0) {
sceneFilename = "";
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
if (onProgress === void 0) {
onProgress = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
return new Promise(function(resolve, reject) {
SceneLoader2.Append(rootUrl, sceneFilename, scene, function(scene2) {
resolve(scene2);
}, onProgress, function(scene2, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
SceneLoader2.LoadAssetContainer = function(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) {
sceneFilename = "";
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
if (onSuccess === void 0) {
onSuccess = null;
}
if (onProgress === void 0) {
onProgress = null;
}
if (onError === void 0) {
onError = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
if (!scene) {
BABYLON2.Tools.Error("No scene available to load asset container to");
return null;
}
var fileInfo = SceneLoader2._getFileInfo(rootUrl, sceneFilename);
if (!fileInfo) {
return null;
}
var loadingToken = {};
scene._addPendingData(loadingToken);
var disposeHandler = function() {
scene._removePendingData(loadingToken);
};
var errorHandler = function(message, exception) {
var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
if (onError) {
onError(scene, errorMessage, exception);
} else {
BABYLON2.Tools.Error(errorMessage);
}
disposeHandler();
};
var progressHandler = onProgress ? function(event) {
try {
onProgress(event);
} catch (e2) {
errorHandler("Error in onProgress callback", e2);
}
} : void 0;
var successHandler = function(assets) {
if (onSuccess) {
try {
onSuccess(assets);
} catch (e2) {
errorHandler("Error in onSuccess callback", e2);
}
}
scene._removePendingData(loadingToken);
};
return SceneLoader2._loadData(fileInfo, scene, function(plugin, data2, responseURL) {
if (plugin.loadAssetContainer) {
var syncedPlugin = plugin;
var assetContainer = syncedPlugin.loadAssetContainer(scene, data2, fileInfo.rootUrl, errorHandler);
if (!assetContainer) {
return;
}
scene.loadingPluginName = plugin.name;
successHandler(assetContainer);
} else if (plugin.loadAssetContainerAsync) {
var asyncedPlugin = plugin;
asyncedPlugin.loadAssetContainerAsync(scene, data2, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function(assetContainer2) {
scene.loadingPluginName = plugin.name;
successHandler(assetContainer2);
}).catch(function(error) {
errorHandler(error.message, error);
});
} else {
errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
}
if (SceneLoader2.ShowLoadingScreen) {
scene.executeWhenReady(function() {
scene.getEngine().hideLoadingUI();
});
}
}, progressHandler, errorHandler, disposeHandler, pluginExtension);
};
SceneLoader2.LoadAssetContainerAsync = function(rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
if (sceneFilename === void 0) {
sceneFilename = "";
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
if (onProgress === void 0) {
onProgress = null;
}
if (pluginExtension === void 0) {
pluginExtension = null;
}
return new Promise(function(resolve, reject) {
SceneLoader2.LoadAssetContainer(rootUrl, sceneFilename, scene, function(assetContainer) {
resolve(assetContainer);
}, onProgress, function(scene2, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
SceneLoader2._ForceFullSceneLoadingForIncremental = false;
SceneLoader2._ShowLoadingScreen = true;
SceneLoader2._CleanBoneMatrixWeights = false;
SceneLoader2.NO_LOGGING = 0;
SceneLoader2.MINIMAL_LOGGING = 1;
SceneLoader2.SUMMARY_LOGGING = 2;
SceneLoader2.DETAILED_LOGGING = 3;
SceneLoader2._loggingLevel = SceneLoader2.NO_LOGGING;
SceneLoader2.OnPluginActivatedObservable = new BABYLON2.Observable();
SceneLoader2._registeredPlugins = {};
return SceneLoader2;
}()
);
BABYLON2.SceneLoader = SceneLoader;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var parseMaterialById = function(id, parsedData, scene, rootUrl) {
for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
var parsedMaterial = parsedData.materials[index];
if (parsedMaterial.id === id) {
return BABYLON2.Material.Parse(parsedMaterial, scene, rootUrl);
}
}
return null;
};
var isDescendantOf = function(mesh2, names, hierarchyIds) {
for (var i2 in names) {
if (mesh2.name === names[i2]) {
hierarchyIds.push(mesh2.id);
return true;
}
}
if (mesh2.parentId && hierarchyIds.indexOf(mesh2.parentId) !== -1) {
hierarchyIds.push(mesh2.id);
return true;
}
return false;
};
var logOperation = function(operation, producer) {
return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
};
var loadAssetContainer = function(scene, data2, rootUrl, onError, addToScene) {
if (addToScene === void 0) {
addToScene = false;
}
var container = new BABYLON2.AssetContainer(scene);
var log = "importScene has failed JSON parse";
try {
var parsedData = JSON.parse(data2);
log = "";
var fullDetails = BABYLON2.SceneLoader.loggingLevel === BABYLON2.SceneLoader.DETAILED_LOGGING;
var index;
var cache;
if (parsedData.lights !== void 0 && parsedData.lights !== null) {
for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
var parsedLight = parsedData.lights[index];
var light = BABYLON2.Light.Parse(parsedLight, scene);
if (light) {
container.lights.push(light);
log += index === 0 ? "\n Lights:" : "";
log += "\n " + light.toString(fullDetails);
}
}
}
if (parsedData.animations !== void 0 && parsedData.animations !== null) {
for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
var parsedAnimation = parsedData.animations[index];
var animation = BABYLON2.Animation.Parse(parsedAnimation);
scene.animations.push(animation);
container.animations.push(animation);
log += index === 0 ? "\n Animations:" : "";
log += "\n " + animation.toString(fullDetails);
}
}
if (parsedData.materials !== void 0 && parsedData.materials !== null) {
for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
var parsedMaterial = parsedData.materials[index];
var mat = BABYLON2.Material.Parse(parsedMaterial, scene, rootUrl);
container.materials.push(mat);
log += index === 0 ? "\n Materials:" : "";
log += "\n " + mat.toString(fullDetails);
}
}
if (parsedData.multiMaterials !== void 0 && parsedData.multiMaterials !== null) {
for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
var parsedMultiMaterial = parsedData.multiMaterials[index];
var mmat = BABYLON2.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
container.multiMaterials.push(mmat);
log += index === 0 ? "\n MultiMaterials:" : "";
log += "\n " + mmat.toString(fullDetails);
}
}
if (parsedData.morphTargetManagers !== void 0 && parsedData.morphTargetManagers !== null) {
for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
var managerData = _a[_i];
container.morphTargetManagers.push(BABYLON2.MorphTargetManager.Parse(managerData, scene));
}
}
if (parsedData.skeletons !== void 0 && parsedData.skeletons !== null) {
for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
var parsedSkeleton = parsedData.skeletons[index];
var skeleton = BABYLON2.Skeleton.Parse(parsedSkeleton, scene);
container.skeletons.push(skeleton);
log += index === 0 ? "\n Skeletons:" : "";
log += "\n " + skeleton.toString(fullDetails);
}
}
var geometries = parsedData.geometries;
if (geometries !== void 0 && geometries !== null) {
var addedGeometry = new Array();
var boxes = geometries.boxes;
if (boxes !== void 0 && boxes !== null) {
for (index = 0, cache = boxes.length; index < cache; index++) {
var parsedBox = boxes[index];
addedGeometry.push(BABYLON2.BoxGeometry.Parse(parsedBox, scene));
}
}
var spheres = geometries.spheres;
if (spheres !== void 0 && spheres !== null) {
for (index = 0, cache = spheres.length; index < cache; index++) {
var parsedSphere = spheres[index];
addedGeometry.push(BABYLON2.SphereGeometry.Parse(parsedSphere, scene));
}
}
var cylinders = geometries.cylinders;
if (cylinders !== void 0 && cylinders !== null) {
for (index = 0, cache = cylinders.length; index < cache; index++) {
var parsedCylinder = cylinders[index];
addedGeometry.push(BABYLON2.CylinderGeometry.Parse(parsedCylinder, scene));
}
}
var toruses = geometries.toruses;
if (toruses !== void 0 && toruses !== null) {
for (index = 0, cache = toruses.length; index < cache; index++) {
var parsedTorus = toruses[index];
addedGeometry.push(BABYLON2.TorusGeometry.Parse(parsedTorus, scene));
}
}
var grounds = geometries.grounds;
if (grounds !== void 0 && grounds !== null) {
for (index = 0, cache = grounds.length; index < cache; index++) {
var parsedGround = grounds[index];
addedGeometry.push(BABYLON2.GroundGeometry.Parse(parsedGround, scene));
}
}
var planes = geometries.planes;
if (planes !== void 0 && planes !== null) {
for (index = 0, cache = planes.length; index < cache; index++) {
var parsedPlane = planes[index];
addedGeometry.push(BABYLON2.PlaneGeometry.Parse(parsedPlane, scene));
}
}
var torusKnots = geometries.torusKnots;
if (torusKnots !== void 0 && torusKnots !== null) {
for (index = 0, cache = torusKnots.length; index < cache; index++) {
var parsedTorusKnot = torusKnots[index];
addedGeometry.push(BABYLON2.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
}
}
var vertexData = geometries.vertexData;
if (vertexData !== void 0 && vertexData !== null) {
for (index = 0, cache = vertexData.length; index < cache; index++) {
var parsedVertexData = vertexData[index];
addedGeometry.push(BABYLON2.Geometry.Parse(parsedVertexData, scene, rootUrl));
}
}
addedGeometry.forEach(function(g) {
if (g) {
container.geometries.push(g);
}
});
}
if (parsedData.transformNodes !== void 0 && parsedData.transformNodes !== null) {
for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
var parsedTransformNode = parsedData.transformNodes[index];
var node = BABYLON2.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
container.transformNodes.push(node);
}
}
if (parsedData.meshes !== void 0 && parsedData.meshes !== null) {
for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
var parsedMesh = parsedData.meshes[index];
var mesh2 = BABYLON2.Mesh.Parse(parsedMesh, scene, rootUrl);
container.meshes.push(mesh2);
log += index === 0 ? "\n Meshes:" : "";
log += "\n " + mesh2.toString(fullDetails);
}
}
if (parsedData.cameras !== void 0 && parsedData.cameras !== null) {
for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
var parsedCamera = parsedData.cameras[index];
var camera2 = BABYLON2.Camera.Parse(parsedCamera, scene);
container.cameras.push(camera2);
log += index === 0 ? "\n Cameras:" : "";
log += "\n " + camera2.toString(fullDetails);
}
}
if (parsedData.animationGroups !== void 0 && parsedData.animationGroups !== null) {
for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
var parsedAnimationGroup = parsedData.animationGroups[index];
var animationGroup = BABYLON2.AnimationGroup.Parse(parsedAnimationGroup, scene);
container.animationGroups.push(animationGroup);
log += index === 0 ? "\n AnimationGroups:" : "";
log += "\n " + animationGroup.toString(fullDetails);
}
}
for (index = 0, cache = scene.cameras.length; index < cache; index++) {
var camera2 = scene.cameras[index];
if (camera2._waitingParentId) {
camera2.parent = scene.getLastEntryByID(camera2._waitingParentId);
camera2._waitingParentId = null;
}
}
for (index = 0, cache = scene.lights.length; index < cache; index++) {
var light_1 = scene.lights[index];
if (light_1 && light_1._waitingParentId) {
light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
light_1._waitingParentId = null;
}
}
for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
var transformNode = scene.transformNodes[index];
if (transformNode._waitingParentId) {
transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
transformNode._waitingParentId = null;
}
}
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
var mesh2 = scene.meshes[index];
if (mesh2._waitingParentId) {
mesh2.parent = scene.getLastEntryByID(mesh2._waitingParentId);
mesh2._waitingParentId = null;
}
}
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
var currentMesh = scene.meshes[index];
if (currentMesh._waitingFreezeWorldMatrix) {
currentMesh.freezeWorldMatrix();
currentMesh._waitingFreezeWorldMatrix = null;
} else {
currentMesh.computeWorldMatrix(true);
}
}
for (index = 0, cache = scene.lights.length; index < cache; index++) {
var light_2 = scene.lights[index];
if (light_2._excludedMeshesIds.length > 0) {
for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
if (excludedMesh) {
light_2.excludedMeshes.push(excludedMesh);
}
}
light_2._excludedMeshesIds = [];
}
if (light_2._includedOnlyMeshesIds.length > 0) {
for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
if (includedOnlyMesh) {
light_2.includedOnlyMeshes.push(includedOnlyMesh);
}
}
light_2._includedOnlyMeshesIds = [];
}
}
BABYLON2.AbstractScene.Parse(parsedData, scene, container, rootUrl);
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
var mesh2 = scene.meshes[index];
if (mesh2._waitingActions) {
BABYLON2.ActionManager.Parse(mesh2._waitingActions, mesh2, scene);
mesh2._waitingActions = null;
}
}
if (parsedData.actions !== void 0 && parsedData.actions !== null) {
BABYLON2.ActionManager.Parse(parsedData.actions, null, scene);
}
if (!addToScene) {
container.removeAllFromScene();
}
} catch (err) {
var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
if (onError) {
onError(msg, err);
} else {
BABYLON2.Tools.Log(msg);
throw err;
}
} finally {
if (log !== null && BABYLON2.SceneLoader.loggingLevel !== BABYLON2.SceneLoader.NO_LOGGING) {
BABYLON2.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON2.SceneLoader.loggingLevel !== BABYLON2.SceneLoader.MINIMAL_LOGGING ? log : ""));
}
}
return container;
};
BABYLON2.SceneLoader.RegisterPlugin({
name: "babylon.js",
extensions: ".babylon",
canDirectLoad: function(data2) {
if (data2.indexOf("babylon") !== -1) {
return true;
}
return false;
},
importMesh: function(meshesNames, scene, data2, rootUrl, meshes, particleSystems, skeletons, onError) {
var log = "importMesh has failed JSON parse";
try {
var parsedData = JSON.parse(data2);
log = "";
var fullDetails = BABYLON2.SceneLoader.loggingLevel === BABYLON2.SceneLoader.DETAILED_LOGGING;
if (!meshesNames) {
meshesNames = null;
} else if (!Array.isArray(meshesNames)) {
meshesNames = [meshesNames];
}
var hierarchyIds = new Array();
if (parsedData.meshes !== void 0 && parsedData.meshes !== null) {
var loadedSkeletonsIds = [];
var loadedMaterialsIds = [];
var index;
var cache;
for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
var parsedMesh = parsedData.meshes[index];
if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
if (meshesNames !== null) {
delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
}
if (parsedMesh.geometryId !== void 0 && parsedMesh.geometryId !== null) {
if (parsedData.geometries !== void 0 && parsedData.geometries !== null) {
var found = false;
["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function(geometryType) {
if (found === true || !parsedData.geometries[geometryType] || !Array.isArray(parsedData.geometries[geometryType])) {
return;
} else {
parsedData.geometries[geometryType].forEach(function(parsedGeometryData) {
if (parsedGeometryData.id === parsedMesh.geometryId) {
switch (geometryType) {
case "boxes":
BABYLON2.BoxGeometry.Parse(parsedGeometryData, scene);
break;
case "spheres":
BABYLON2.SphereGeometry.Parse(parsedGeometryData, scene);
break;
case "cylinders":
BABYLON2.CylinderGeometry.Parse(parsedGeometryData, scene);
break;
case "toruses":
BABYLON2.TorusGeometry.Parse(parsedGeometryData, scene);
break;
case "grounds":
BABYLON2.GroundGeometry.Parse(parsedGeometryData, scene);
break;
case "planes":
BABYLON2.PlaneGeometry.Parse(parsedGeometryData, scene);
break;
case "torusKnots":
BABYLON2.TorusKnotGeometry.Parse(parsedGeometryData, scene);
break;
case "vertexData":
BABYLON2.Geometry.Parse(parsedGeometryData, scene, rootUrl);
break;
}
found = true;
}
});
}
});
if (found === false) {
BABYLON2.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
}
}
}
if (parsedMesh.materialId) {
var materialFound = loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1;
if (materialFound === false && parsedData.multiMaterials !== void 0 && parsedData.multiMaterials !== null) {
for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
if (parsedMultiMaterial.id === parsedMesh.materialId) {
for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
var subMatId = parsedMultiMaterial.materials[matIndex];
loadedMaterialsIds.push(subMatId);
var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
if (mat) {
log += "\n Material " + mat.toString(fullDetails);
}
}
loadedMaterialsIds.push(parsedMultiMaterial.id);
var mmat = BABYLON2.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
if (mmat) {
materialFound = true;
log += "\n Multi-Material " + mmat.toString(fullDetails);
}
break;
}
}
}
if (materialFound === false) {
loadedMaterialsIds.push(parsedMesh.materialId);
var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
if (!mat) {
BABYLON2.Tools.Warn("Material not found for mesh " + parsedMesh.id);
} else {
log += "\n Material " + mat.toString(fullDetails);
}
}
}
if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== void 0 && parsedData.skeletons !== null) {
var skeletonAlreadyLoaded = loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1;
if (skeletonAlreadyLoaded === false) {
for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
var parsedSkeleton = parsedData.skeletons[skeletonIndex];
if (parsedSkeleton.id === parsedMesh.skeletonId) {
var skeleton = BABYLON2.Skeleton.Parse(parsedSkeleton, scene);
skeletons.push(skeleton);
loadedSkeletonsIds.push(parsedSkeleton.id);
log += "\n Skeleton " + skeleton.toString(fullDetails);
}
}
}
}
if (parsedData.morphTargetManagers !== void 0 && parsedData.morphTargetManagers !== null) {
for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
var managerData = _a[_i];
BABYLON2.MorphTargetManager.Parse(managerData, scene);
}
}
var mesh2 = BABYLON2.Mesh.Parse(parsedMesh, scene, rootUrl);
meshes.push(mesh2);
log += "\n Mesh " + mesh2.toString(fullDetails);
}
}
var currentMesh;
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
currentMesh = scene.meshes[index];
if (currentMesh._waitingParentId) {
currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
currentMesh._waitingParentId = null;
}
}
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
currentMesh = scene.meshes[index];
if (currentMesh._waitingFreezeWorldMatrix) {
currentMesh.freezeWorldMatrix();
currentMesh._waitingFreezeWorldMatrix = null;
} else {
currentMesh.computeWorldMatrix(true);
}
}
}
if (parsedData.particleSystems !== void 0 && parsedData.particleSystems !== null) {
var parser = BABYLON2.AbstractScene.GetIndividualParser(BABYLON2.SceneComponentConstants.NAME_PARTICLESYSTEM);
if (parser) {
for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
var parsedParticleSystem = parsedData.particleSystems[index];
if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
}
}
}
}
return true;
} catch (err) {
var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
if (onError) {
onError(msg, err);
} else {
BABYLON2.Tools.Log(msg);
throw err;
}
} finally {
if (log !== null && BABYLON2.SceneLoader.loggingLevel !== BABYLON2.SceneLoader.NO_LOGGING) {
BABYLON2.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON2.SceneLoader.loggingLevel !== BABYLON2.SceneLoader.MINIMAL_LOGGING ? log : ""));
}
}
return false;
},
load: function(scene, data2, rootUrl, onError) {
var log = "importScene has failed JSON parse";
try {
var parsedData = JSON.parse(data2);
log = "";
if (parsedData.useDelayedTextureLoading !== void 0 && parsedData.useDelayedTextureLoading !== null) {
scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON2.SceneLoader.ForceFullSceneLoadingForIncremental;
}
if (parsedData.autoClear !== void 0 && parsedData.autoClear !== null) {
scene.autoClear = parsedData.autoClear;
}
if (parsedData.clearColor !== void 0 && parsedData.clearColor !== null) {
scene.clearColor = BABYLON2.Color4.FromArray(parsedData.clearColor);
}
if (parsedData.ambientColor !== void 0 && parsedData.ambientColor !== null) {
scene.ambientColor = BABYLON2.Color3.FromArray(parsedData.ambientColor);
}
if (parsedData.gravity !== void 0 && parsedData.gravity !== null) {
scene.gravity = BABYLON2.Vector3.FromArray(parsedData.gravity);
}
if (parsedData.fogMode && parsedData.fogMode !== 0) {
scene.fogMode = parsedData.fogMode;
scene.fogColor = BABYLON2.Color3.FromArray(parsedData.fogColor);
scene.fogStart = parsedData.fogStart;
scene.fogEnd = parsedData.fogEnd;
scene.fogDensity = parsedData.fogDensity;
log += " Fog mode for scene: ";
switch (scene.fogMode) {
case 1:
log += "exp\n";
break;
case 2:
log += "exp2\n";
break;
case 3:
log += "linear\n";
break;
}
}
if (parsedData.physicsEnabled) {
var physicsPlugin;
if (parsedData.physicsEngine === "cannon") {
physicsPlugin = new BABYLON2.CannonJSPlugin();
} else if (parsedData.physicsEngine === "oimo") {
physicsPlugin = new BABYLON2.OimoJSPlugin();
}
log = " Physics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
var physicsGravity = parsedData.physicsGravity ? BABYLON2.Vector3.FromArray(parsedData.physicsGravity) : null;
scene.enablePhysics(physicsGravity, physicsPlugin);
}
if (parsedData.metadata !== void 0 && parsedData.metadata !== null) {
scene.metadata = parsedData.metadata;
}
if (parsedData.collisionsEnabled !== void 0 && parsedData.collisionsEnabled !== null) {
scene.collisionsEnabled = parsedData.collisionsEnabled;
}
scene.workerCollisions = !!parsedData.workerCollisions;
var container = loadAssetContainer(scene, data2, rootUrl, onError, true);
if (!container) {
return false;
}
if (parsedData.autoAnimate) {
scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1);
}
if (parsedData.activeCameraID !== void 0 && parsedData.activeCameraID !== null) {
scene.setActiveCameraByID(parsedData.activeCameraID);
}
if (parsedData.environmentTexture !== void 0 && parsedData.environmentTexture !== null) {
if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
var hdrSize = parsedData.environmentTextureSize ? parsedData.environmentTextureSize : 128;
var hdrTexture = new BABYLON2.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
if (parsedData.environmentTextureRotationY) {
hdrTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = hdrTexture;
} else {
var cubeTexture = BABYLON2.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
if (parsedData.environmentTextureRotationY) {
cubeTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = cubeTexture;
}
if (parsedData.createDefaultSkybox === true) {
var skyboxScale = scene.activeCamera !== void 0 && scene.activeCamera !== null ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1e3;
var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
scene.createDefaultSkybox(void 0, true, skyboxScale, skyboxBlurLevel);
}
}
return true;
} catch (err) {
var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
if (onError) {
onError(msg, err);
} else {
BABYLON2.Tools.Log(msg);
throw err;
}
} finally {
if (log !== null && BABYLON2.SceneLoader.loggingLevel !== BABYLON2.SceneLoader.NO_LOGGING) {
BABYLON2.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON2.SceneLoader.loggingLevel !== BABYLON2.SceneLoader.MINIMAL_LOGGING ? log : ""));
}
}
return false;
},
loadAssetContainer: function(scene, data2, rootUrl, onError) {
var container = loadAssetContainer(scene, data2, rootUrl, onError);
return container;
}
});
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FilesInput = (
/** @class */
function() {
function FilesInput2(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback2) {
this.onProcessFileCallback = function() {
return true;
};
this._engine = engine;
this._currentScene = scene;
this._sceneLoadedCallback = sceneLoadedCallback;
this._progressCallback = progressCallback;
this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
this._textureLoadingCallback = textureLoadingCallback;
this._startingProcessingFilesCallback = startingProcessingFilesCallback;
this._onReloadCallback = onReloadCallback;
this._errorCallback = errorCallback2;
}
FilesInput2.prototype.monitorElementForDragNDrop = function(elementToMonitor) {
var _this = this;
if (elementToMonitor) {
this._elementToMonitor = elementToMonitor;
this._dragEnterHandler = function(e2) {
_this.drag(e2);
};
this._dragOverHandler = function(e2) {
_this.drag(e2);
};
this._dropHandler = function(e2) {
_this.drop(e2);
};
this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
}
};
FilesInput2.prototype.dispose = function() {
if (!this._elementToMonitor) {
return;
}
this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
this._elementToMonitor.removeEventListener("drop", this._dropHandler);
};
FilesInput2.prototype.renderFunction = function() {
if (this._additionalRenderLoopLogicCallback) {
this._additionalRenderLoopLogicCallback();
}
if (this._currentScene) {
if (this._textureLoadingCallback) {
var remaining = this._currentScene.getWaitingItemsCount();
if (remaining > 0) {
this._textureLoadingCallback(remaining);
}
}
this._currentScene.render();
}
};
FilesInput2.prototype.drag = function(e2) {
e2.stopPropagation();
e2.preventDefault();
};
FilesInput2.prototype.drop = function(eventDrop) {
eventDrop.stopPropagation();
eventDrop.preventDefault();
this.loadFiles(eventDrop);
};
FilesInput2.prototype._traverseFolder = function(folder, files, remaining, callback) {
var _this = this;
var reader = folder.createReader();
var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
reader.readEntries(function(entries) {
remaining.count += entries.length;
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
var entry = entries_1[_i];
if (entry.isFile) {
entry.file(function(file) {
file.correctName = relativePath + file.name;
files.push(file);
if (--remaining.count === 0) {
callback();
}
});
} else if (entry.isDirectory) {
_this._traverseFolder(entry, files, remaining, callback);
}
}
if (--remaining.count) {
callback();
}
});
};
FilesInput2.prototype._processFiles = function(files) {
for (var i2 = 0; i2 < files.length; i2++) {
var name = files[i2].correctName.toLowerCase();
var extension = name.split(".").pop();
if (!this.onProcessFileCallback(files[i2], name, extension)) {
continue;
}
if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb") && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
this._sceneFileToLoad = files[i2];
}
FilesInput2.FilesToLoad[name] = files[i2];
}
};
FilesInput2.prototype.loadFiles = function(event) {
var _this = this;
if (event && event.dataTransfer && event.dataTransfer.files) {
this._filesToLoad = event.dataTransfer.files;
}
if (event && event.target && event.target.files) {
this._filesToLoad = event.target.files;
}
if (!this._filesToLoad || this._filesToLoad.length === 0) {
return;
}
if (this._startingProcessingFilesCallback) {
this._startingProcessingFilesCallback(this._filesToLoad);
}
if (this._filesToLoad && this._filesToLoad.length > 0) {
var files_1 = new Array();
var folders = [];
var items = event.dataTransfer ? event.dataTransfer.items : null;
for (var i2 = 0; i2 < this._filesToLoad.length; i2++) {
var fileToLoad = this._filesToLoad[i2];
var name_1 = fileToLoad.name.toLowerCase();
var entry = void 0;
fileToLoad.correctName = name_1;
if (items) {
var item = items[i2];
if (item.getAsEntry) {
entry = item.getAsEntry();
} else if (item.webkitGetAsEntry) {
entry = item.webkitGetAsEntry();
}
}
if (!entry) {
files_1.push(fileToLoad);
} else {
if (entry.isDirectory) {
folders.push(entry);
} else {
files_1.push(fileToLoad);
}
}
}
if (folders.length === 0) {
this._processFiles(files_1);
this._processReload();
} else {
var remaining = { count: folders.length };
for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
var folder = folders_1[_i];
this._traverseFolder(folder, files_1, remaining, function() {
_this._processFiles(files_1);
if (remaining.count === 0) {
_this._processReload();
}
});
}
}
}
};
FilesInput2.prototype._processReload = function() {
if (this._onReloadCallback) {
this._onReloadCallback(this._sceneFileToLoad);
} else {
this.reload();
}
};
FilesInput2.prototype.reload = function() {
var _this = this;
if (this._sceneFileToLoad) {
if (this._currentScene) {
if (BABYLON2.Tools.errorsCount > 0) {
BABYLON2.Tools.ClearLogCache();
}
this._engine.stopRenderLoop();
}
BABYLON2.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function(progress) {
if (_this._progressCallback) {
_this._progressCallback(progress);
}
}).then(function(scene) {
if (_this._currentScene) {
_this._currentScene.dispose();
}
_this._currentScene = scene;
if (_this._sceneLoadedCallback) {
_this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
}
_this._currentScene.executeWhenReady(function() {
_this._engine.runRenderLoop(function() {
_this.renderFunction();
});
});
}).catch(function(error) {
if (_this._errorCallback) {
_this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
}
});
} else {
BABYLON2.Tools.Error("Please provide a valid .babylon file.");
}
};
FilesInput2.FilesToLoad = {};
return FilesInput2;
}()
);
BABYLON2.FilesInput = FilesInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Tags = (
/** @class */
function() {
function Tags2() {
}
Tags2.EnableFor = function(obj) {
obj._tags = obj._tags || {};
obj.hasTags = function() {
return Tags2.HasTags(obj);
};
obj.addTags = function(tagsString) {
return Tags2.AddTagsTo(obj, tagsString);
};
obj.removeTags = function(tagsString) {
return Tags2.RemoveTagsFrom(obj, tagsString);
};
obj.matchesTagsQuery = function(tagsQuery) {
return Tags2.MatchesQuery(obj, tagsQuery);
};
};
Tags2.DisableFor = function(obj) {
delete obj._tags;
delete obj.hasTags;
delete obj.addTags;
delete obj.removeTags;
delete obj.matchesTagsQuery;
};
Tags2.HasTags = function(obj) {
if (!obj._tags) {
return false;
}
return !BABYLON2.Tools.IsEmpty(obj._tags);
};
Tags2.GetTags = function(obj, asString) {
if (asString === void 0) {
asString = true;
}
if (!obj._tags) {
return null;
}
if (asString) {
var tagsArray = [];
for (var tag in obj._tags) {
if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
tagsArray.push(tag);
}
}
return tagsArray.join(" ");
} else {
return obj._tags;
}
};
Tags2.AddTagsTo = function(obj, tagsString) {
if (!tagsString) {
return;
}
if (typeof tagsString !== "string") {
return;
}
var tags = tagsString.split(" ");
tags.forEach(function(tag, index, array) {
Tags2._AddTagTo(obj, tag);
});
};
Tags2._AddTagTo = function(obj, tag) {
tag = tag.trim();
if (tag === "" || tag === "true" || tag === "false") {
return;
}
if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
return;
}
Tags2.EnableFor(obj);
obj._tags[tag] = true;
};
Tags2.RemoveTagsFrom = function(obj, tagsString) {
if (!Tags2.HasTags(obj)) {
return;
}
var tags = tagsString.split(" ");
for (var t in tags) {
Tags2._RemoveTagFrom(obj, tags[t]);
}
};
Tags2._RemoveTagFrom = function(obj, tag) {
delete obj._tags[tag];
};
Tags2.MatchesQuery = function(obj, tagsQuery) {
if (tagsQuery === void 0) {
return true;
}
if (tagsQuery === "") {
return Tags2.HasTags(obj);
}
return BABYLON2.AndOrNotEvaluator.Eval(tagsQuery, function(r) {
return Tags2.HasTags(obj) && obj._tags[r];
});
};
return Tags2;
}()
);
BABYLON2.Tags = Tags;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var AndOrNotEvaluator = (
/** @class */
function() {
function AndOrNotEvaluator2() {
}
AndOrNotEvaluator2.Eval = function(query, evaluateCallback) {
if (!query.match(/\([^\(\)]*\)/g)) {
query = AndOrNotEvaluator2._HandleParenthesisContent(query, evaluateCallback);
} else {
query = query.replace(/\([^\(\)]*\)/g, function(r) {
r = r.slice(1, r.length - 1);
return AndOrNotEvaluator2._HandleParenthesisContent(r, evaluateCallback);
});
}
if (query === "true") {
return true;
}
if (query === "false") {
return false;
}
return AndOrNotEvaluator2.Eval(query, evaluateCallback);
};
AndOrNotEvaluator2._HandleParenthesisContent = function(parenthesisContent, evaluateCallback) {
evaluateCallback = evaluateCallback || function(r) {
return r === "true" ? true : false;
};
var result;
var or = parenthesisContent.split("||");
for (var i2 in or) {
if (or.hasOwnProperty(i2)) {
var ori = AndOrNotEvaluator2._SimplifyNegation(or[i2].trim());
var and = ori.split("&&");
if (and.length > 1) {
for (var j = 0; j < and.length; ++j) {
var andj = AndOrNotEvaluator2._SimplifyNegation(and[j].trim());
if (andj !== "true" && andj !== "false") {
if (andj[0] === "!") {
result = !evaluateCallback(andj.substring(1));
} else {
result = evaluateCallback(andj);
}
} else {
result = andj === "true" ? true : false;
}
if (!result) {
ori = "false";
break;
}
}
}
if (result || ori === "true") {
result = true;
break;
}
if (ori !== "true" && ori !== "false") {
if (ori[0] === "!") {
result = !evaluateCallback(ori.substring(1));
} else {
result = evaluateCallback(ori);
}
} else {
result = ori === "true" ? true : false;
}
}
}
return result ? "true" : "false";
};
AndOrNotEvaluator2._SimplifyNegation = function(booleanString) {
booleanString = booleanString.replace(/^[\s!]+/, function(r) {
r = r.replace(/[\s]/g, function() {
return "";
});
return r.length % 2 ? "!" : "";
});
booleanString = booleanString.trim();
if (booleanString === "!true") {
booleanString = "false";
} else if (booleanString === "!false") {
booleanString = "true";
}
return booleanString;
};
return AndOrNotEvaluator2;
}()
);
BABYLON2.AndOrNotEvaluator = AndOrNotEvaluator;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Database = (
/** @class */
function() {
function Database2(urlToScene, callbackManifestChecked, disableManifestCheck) {
if (disableManifestCheck === void 0) {
disableManifestCheck = false;
}
var _this = this;
this.idbFactory = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
this.callbackManifestChecked = callbackManifestChecked;
this.currentSceneUrl = Database2._ReturnFullUrlLocation(urlToScene);
this.db = null;
this._enableSceneOffline = false;
this._enableTexturesOffline = false;
this.manifestVersionFound = 0;
this.mustUpdateRessources = false;
this.hasReachedQuota = false;
if (!Database2.IDBStorageEnabled) {
this.callbackManifestChecked(true);
} else {
if (disableManifestCheck) {
this._enableSceneOffline = true;
this._enableTexturesOffline = true;
this.manifestVersionFound = 1;
BABYLON2.Tools.SetImmediate(function() {
_this.callbackManifestChecked(true);
});
} else {
this._checkManifestFile();
}
}
}
Object.defineProperty(Database2.prototype, "enableSceneOffline", {
/**
* Gets a boolean indicating if scene must be saved in the database
*/
get: function() {
return this._enableSceneOffline;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Database2.prototype, "enableTexturesOffline", {
/**
* Gets a boolean indicating if textures must be saved in the database
*/
get: function() {
return this._enableTexturesOffline;
},
enumerable: true,
configurable: true
});
Database2.prototype._checkManifestFile = function() {
var _this = this;
var noManifestFile = function() {
_this._enableSceneOffline = false;
_this._enableTexturesOffline = false;
_this.callbackManifestChecked(false);
};
var timeStampUsed = false;
var manifestURL = this.currentSceneUrl + ".manifest";
var xhr = new XMLHttpRequest();
if (navigator.onLine) {
timeStampUsed = true;
manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
}
xhr.open("GET", manifestURL, true);
xhr.addEventListener("load", function() {
if (xhr.status === 200 || BABYLON2.Tools.ValidateXHRData(xhr, 1)) {
try {
var manifestFile = JSON.parse(xhr.response);
_this._enableSceneOffline = manifestFile.enableSceneOffline;
_this._enableTexturesOffline = manifestFile.enableTexturesOffline;
if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
_this.manifestVersionFound = manifestFile.version;
}
if (_this.callbackManifestChecked) {
_this.callbackManifestChecked(true);
}
} catch (ex) {
noManifestFile();
}
} else {
noManifestFile();
}
}, false);
xhr.addEventListener("error", function(event) {
if (timeStampUsed) {
timeStampUsed = false;
var retryManifestURL = _this.currentSceneUrl + ".manifest";
xhr.open("GET", retryManifestURL, true);
xhr.send();
} else {
noManifestFile();
}
}, false);
try {
xhr.send();
} catch (ex) {
BABYLON2.Tools.Error("Error on XHR send request.");
this.callbackManifestChecked(false);
}
};
Database2.prototype.openAsync = function(successCallback2, errorCallback2) {
var _this = this;
var handleError = function() {
_this.isSupported = false;
if (errorCallback2) {
errorCallback2();
}
};
if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
this.isSupported = false;
if (errorCallback2) {
errorCallback2();
}
} else {
if (!this.db) {
this.hasReachedQuota = false;
this.isSupported = true;
var request = this.idbFactory.open("babylonjs", 1);
request.onerror = function(event) {
handleError();
};
request.onblocked = function(event) {
BABYLON2.Tools.Error("IDB request blocked. Please reload the page.");
handleError();
};
request.onsuccess = function(event) {
_this.db = request.result;
successCallback2();
};
request.onupgradeneeded = function(event) {
_this.db = event.target.result;
if (_this.db) {
try {
_this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
_this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
_this.db.createObjectStore("textures", { keyPath: "textureUrl" });
} catch (ex) {
BABYLON2.Tools.Error("Error while creating object stores. Exception: " + ex.message);
handleError();
}
}
};
} else {
if (successCallback2) {
successCallback2();
}
}
}
};
Database2.prototype.loadImageFromDB = function(url, image) {
var _this = this;
var completeURL = Database2._ReturnFullUrlLocation(url);
var saveAndLoadImage = function() {
if (!_this.hasReachedQuota && _this.db !== null) {
_this._saveImageIntoDBAsync(completeURL, image);
} else {
image.src = url;
}
};
if (!this.mustUpdateRessources) {
this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
} else {
saveAndLoadImage();
}
};
Database2.prototype._loadImageFromDBAsync = function(url, image, notInDBCallback) {
if (this.isSupported && this.db !== null) {
var texture;
var transaction = this.db.transaction(["textures"]);
transaction.onabort = function(event) {
image.src = url;
};
transaction.oncomplete = function(event) {
var blobTextureURL;
if (texture) {
var URL2 = window.URL || window.webkitURL;
blobTextureURL = URL2.createObjectURL(texture.data);
image.onerror = function() {
BABYLON2.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
image.src = url;
};
image.src = blobTextureURL;
} else {
notInDBCallback();
}
};
var getRequest2 = transaction.objectStore("textures").get(url);
getRequest2.onsuccess = function(event) {
texture = event.target.result;
};
getRequest2.onerror = function(event) {
BABYLON2.Tools.Error("Error loading texture " + url + " from DB.");
image.src = url;
};
} else {
BABYLON2.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
image.src = url;
}
};
Database2.prototype._saveImageIntoDBAsync = function(url, image) {
var _this = this;
if (this.isSupported) {
var generateBlobUrl = function() {
var blobTextureURL;
if (blob2) {
var URL2 = window.URL || window.webkitURL;
try {
blobTextureURL = URL2.createObjectURL(blob2);
} catch (ex) {
blobTextureURL = URL2.createObjectURL(blob2);
}
}
if (blobTextureURL) {
image.src = blobTextureURL;
}
};
if (Database2.IsUASupportingBlobStorage) {
var xhr = new XMLHttpRequest(), blob2;
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.addEventListener("load", function() {
if (xhr.status === 200 && _this.db) {
blob2 = xhr.response;
var transaction = _this.db.transaction(["textures"], "readwrite");
transaction.onabort = function(event) {
try {
var srcElement = event.srcElement || event.target;
var error = srcElement.error;
if (error && error.name === "QuotaExceededError") {
_this.hasReachedQuota = true;
}
} catch (ex) {
}
generateBlobUrl();
};
transaction.oncomplete = function(event) {
generateBlobUrl();
};
var newTexture = { textureUrl: url, data: blob2 };
try {
var addRequest = transaction.objectStore("textures").put(newTexture);
addRequest.onsuccess = function(event) {
};
addRequest.onerror = function(event) {
generateBlobUrl();
};
} catch (ex) {
if (ex.code === 25) {
Database2.IsUASupportingBlobStorage = false;
}
image.src = url;
}
} else {
image.src = url;
}
}, false);
xhr.addEventListener("error", function(event) {
BABYLON2.Tools.Error("Error in XHR request in BABYLON.Database.");
image.src = url;
}, false);
xhr.send();
} else {
image.src = url;
}
} else {
BABYLON2.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
image.src = url;
}
};
Database2.prototype._checkVersionFromDB = function(url, versionLoaded) {
var _this = this;
var updateVersion = function() {
_this._saveVersionIntoDBAsync(url, versionLoaded);
};
this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
};
Database2.prototype._loadVersionFromDBAsync = function(url, callback, updateInDBCallback) {
var _this = this;
if (this.isSupported && this.db) {
var version2;
try {
var transaction = this.db.transaction(["versions"]);
transaction.oncomplete = function(event) {
if (version2) {
if (_this.manifestVersionFound !== version2.data) {
_this.mustUpdateRessources = true;
updateInDBCallback();
} else {
callback(version2.data);
}
} else {
_this.mustUpdateRessources = true;
updateInDBCallback();
}
};
transaction.onabort = function(event) {
callback(-1);
};
var getRequest2 = transaction.objectStore("versions").get(url);
getRequest2.onsuccess = function(event) {
version2 = event.target.result;
};
getRequest2.onerror = function(event) {
BABYLON2.Tools.Error("Error loading version for scene " + url + " from DB.");
callback(-1);
};
} catch (ex) {
BABYLON2.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
callback(-1);
}
} else {
BABYLON2.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
callback(-1);
}
};
Database2.prototype._saveVersionIntoDBAsync = function(url, callback) {
var _this = this;
if (this.isSupported && !this.hasReachedQuota && this.db) {
try {
var transaction = this.db.transaction(["versions"], "readwrite");
transaction.onabort = function(event) {
try {
var error = event.srcElement["error"];
if (error && error.name === "QuotaExceededError") {
_this.hasReachedQuota = true;
}
} catch (ex) {
}
callback(-1);
};
transaction.oncomplete = function(event) {
callback(_this.manifestVersionFound);
};
var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
var addRequest = transaction.objectStore("versions").put(newVersion);
addRequest.onsuccess = function(event) {
};
addRequest.onerror = function(event) {
BABYLON2.Tools.Error("Error in DB add version request in BABYLON.Database.");
};
} catch (ex) {
BABYLON2.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
callback(-1);
}
} else {
callback(-1);
}
};
Database2.prototype.loadFileFromDB = function(url, sceneLoaded, progressCallBack, errorCallback2, useArrayBuffer) {
var _this = this;
var completeUrl = Database2._ReturnFullUrlLocation(url);
var saveAndLoadFile = function() {
_this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback2);
};
this._checkVersionFromDB(completeUrl, function(version2) {
if (version2 !== -1) {
if (!_this.mustUpdateRessources) {
_this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
} else {
_this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback2);
}
} else {
if (errorCallback2) {
errorCallback2();
}
}
});
};
Database2.prototype._loadFileFromDBAsync = function(url, callback, notInDBCallback, useArrayBuffer) {
if (this.isSupported && this.db) {
var targetStore;
if (url.indexOf(".babylon") !== -1) {
targetStore = "scenes";
} else {
targetStore = "textures";
}
var file;
var transaction = this.db.transaction([targetStore]);
transaction.oncomplete = function(event) {
if (file) {
callback(file.data);
} else {
notInDBCallback();
}
};
transaction.onabort = function(event) {
notInDBCallback();
};
var getRequest2 = transaction.objectStore(targetStore).get(url);
getRequest2.onsuccess = function(event) {
file = event.target.result;
};
getRequest2.onerror = function(event) {
BABYLON2.Tools.Error("Error loading file " + url + " from DB.");
notInDBCallback();
};
} else {
BABYLON2.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
callback();
}
};
Database2.prototype._saveFileIntoDBAsync = function(url, callback, progressCallback, useArrayBuffer, errorCallback2) {
var _this = this;
if (this.isSupported) {
var targetStore;
if (url.indexOf(".babylon") !== -1) {
targetStore = "scenes";
} else {
targetStore = "textures";
}
var xhr = new XMLHttpRequest();
var fileData;
xhr.open("GET", url + "?" + Date.now(), true);
if (useArrayBuffer) {
xhr.responseType = "arraybuffer";
}
if (progressCallback) {
xhr.onprogress = progressCallback;
}
xhr.addEventListener("load", function() {
if (xhr.status === 200 || xhr.status < 400 && BABYLON2.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
if (!_this.hasReachedQuota && _this.db) {
var transaction = _this.db.transaction([targetStore], "readwrite");
transaction.onabort = function(event) {
try {
var error = event.srcElement["error"];
if (error && error.name === "QuotaExceededError") {
_this.hasReachedQuota = true;
}
} catch (ex) {
}
callback(fileData);
};
transaction.oncomplete = function(event) {
callback(fileData);
};
var newFile;
if (targetStore === "scenes") {
newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
} else {
newFile = { textureUrl: url, data: fileData };
}
try {
var addRequest = transaction.objectStore(targetStore).put(newFile);
addRequest.onsuccess = function(event) {
};
addRequest.onerror = function(event) {
BABYLON2.Tools.Error("Error in DB add file request in BABYLON.Database.");
};
} catch (ex) {
callback(fileData);
}
} else {
callback(fileData);
}
} else {
if (xhr.status >= 400 && errorCallback2) {
errorCallback2(xhr);
} else {
callback();
}
}
}, false);
xhr.addEventListener("error", function(event) {
BABYLON2.Tools.Error("error on XHR request.");
callback();
}, false);
xhr.send();
} else {
BABYLON2.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
callback();
}
};
Database2.IsUASupportingBlobStorage = true;
Database2.IDBStorageEnabled = true;
Database2._ParseURL = function(url) {
var a = document.createElement("a");
a.href = url;
var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
var absLocation = url.substring(0, url.indexOf(fileName, 0));
return absLocation;
};
Database2._ReturnFullUrlLocation = function(url) {
if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
return Database2._ParseURL(window.location.href) + url;
} else {
return url;
}
};
return Database2;
}()
);
BABYLON2.Database = Database;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FresnelParameters = (
/** @class */
function() {
function FresnelParameters2() {
this._isEnabled = true;
this.leftColor = BABYLON2.Color3.White();
this.rightColor = BABYLON2.Color3.Black();
this.bias = 0;
this.power = 1;
}
Object.defineProperty(FresnelParameters2.prototype, "isEnabled", {
/**
* Define if the fresnel effect is enable or not.
*/
get: function() {
return this._isEnabled;
},
set: function(value) {
if (this._isEnabled === value) {
return;
}
this._isEnabled = value;
BABYLON2.Engine.MarkAllMaterialsAsDirty(BABYLON2.Material.FresnelDirtyFlag | BABYLON2.Material.MiscDirtyFlag);
},
enumerable: true,
configurable: true
});
FresnelParameters2.prototype.clone = function() {
var newFresnelParameters = new FresnelParameters2();
BABYLON2.Tools.DeepCopy(this, newFresnelParameters);
return newFresnelParameters;
};
FresnelParameters2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.isEnabled = this.isEnabled;
serializationObject.leftColor = this.leftColor.asArray();
serializationObject.rightColor = this.rightColor.asArray();
serializationObject.bias = this.bias;
serializationObject.power = this.power;
return serializationObject;
};
FresnelParameters2.Parse = function(parsedFresnelParameters) {
var fresnelParameters = new FresnelParameters2();
fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
fresnelParameters.leftColor = BABYLON2.Color3.FromArray(parsedFresnelParameters.leftColor);
fresnelParameters.rightColor = BABYLON2.Color3.FromArray(parsedFresnelParameters.rightColor);
fresnelParameters.bias = parsedFresnelParameters.bias;
fresnelParameters.power = parsedFresnelParameters.power || 1;
return fresnelParameters;
};
return FresnelParameters2;
}()
);
BABYLON2.FresnelParameters = FresnelParameters;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MultiMaterial = (
/** @class */
function(_super) {
__extends(MultiMaterial2, _super);
function MultiMaterial2(name, scene) {
var _this = _super.call(this, name, scene, true) || this;
scene.multiMaterials.push(_this);
_this.subMaterials = new Array();
_this.storeEffectOnSubMeshes = true;
return _this;
}
Object.defineProperty(MultiMaterial2.prototype, "subMaterials", {
/**
* Gets or Sets the list of Materials used within the multi material.
* They need to be ordered according to the submeshes order in the associated mesh
*/
get: function() {
return this._subMaterials;
},
set: function(value) {
this._subMaterials = value;
this._hookArray(value);
},
enumerable: true,
configurable: true
});
MultiMaterial2.prototype._hookArray = function(array) {
var _this = this;
var oldPush = array.push;
array.push = function() {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var result = oldPush.apply(array, items);
_this._markAllSubMeshesAsTexturesDirty();
return result;
};
var oldSplice = array.splice;
array.splice = function(index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
_this._markAllSubMeshesAsTexturesDirty();
return deleted;
};
};
MultiMaterial2.prototype.getSubMaterial = function(index) {
if (index < 0 || index >= this.subMaterials.length) {
return this.getScene().defaultMaterial;
}
return this.subMaterials[index];
};
MultiMaterial2.prototype.getActiveTextures = function() {
var _a;
return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function(subMaterial) {
if (subMaterial) {
return subMaterial.getActiveTextures();
} else {
return [];
}
}));
};
MultiMaterial2.prototype.getClassName = function() {
return "MultiMaterial";
};
MultiMaterial2.prototype.isReadyForSubMesh = function(mesh2, subMesh, useInstances) {
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial = this.subMaterials[index];
if (subMaterial) {
if (subMaterial.storeEffectOnSubMeshes) {
if (!subMaterial.isReadyForSubMesh(mesh2, subMesh, useInstances)) {
return false;
}
continue;
}
if (!subMaterial.isReady(mesh2)) {
return false;
}
}
}
return true;
};
MultiMaterial2.prototype.clone = function(name, cloneChildren) {
var newMultiMaterial = new MultiMaterial2(name, this.getScene());
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial = null;
var current = this.subMaterials[index];
if (cloneChildren && current) {
subMaterial = current.clone(name + "-" + current.name);
} else {
subMaterial = this.subMaterials[index];
}
newMultiMaterial.subMaterials.push(subMaterial);
}
return newMultiMaterial;
};
MultiMaterial2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.id = this.id;
if (BABYLON2.Tags) {
serializationObject.tags = BABYLON2.Tags.GetTags(this);
}
serializationObject.materials = [];
for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
var subMat = this.subMaterials[matIndex];
if (subMat) {
serializationObject.materials.push(subMat.id);
} else {
serializationObject.materials.push(null);
}
}
return serializationObject;
};
MultiMaterial2.prototype.dispose = function(forceDisposeEffect, forceDisposeTextures) {
var scene = this.getScene();
if (!scene) {
return;
}
var index = scene.multiMaterials.indexOf(this);
if (index >= 0) {
scene.multiMaterials.splice(index, 1);
}
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
};
return MultiMaterial2;
}(BABYLON2.Material)
);
BABYLON2.MultiMaterial = MultiMaterial;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FreeCameraTouchInput = (
/** @class */
function() {
function FreeCameraTouchInput2() {
this.touchAngularSensibility = 2e5;
this.touchMoveSensibility = 250;
this._offsetX = null;
this._offsetY = null;
this._pointerPressed = new Array();
}
FreeCameraTouchInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
var previousPosition = null;
if (this._pointerInput === void 0) {
this._onLostFocus = function(evt) {
_this._offsetX = null;
_this._offsetY = null;
};
this._pointerInput = function(p, s) {
var evt = p.event;
if (evt.pointerType === "mouse") {
return;
}
if (p.type === BABYLON2.PointerEventTypes.POINTERDOWN) {
if (!noPreventDefault) {
evt.preventDefault();
}
_this._pointerPressed.push(evt.pointerId);
if (_this._pointerPressed.length !== 1) {
return;
}
previousPosition = {
x: evt.clientX,
y: evt.clientY
};
} else if (p.type === BABYLON2.PointerEventTypes.POINTERUP) {
if (!noPreventDefault) {
evt.preventDefault();
}
var index = _this._pointerPressed.indexOf(evt.pointerId);
if (index === -1) {
return;
}
_this._pointerPressed.splice(index, 1);
if (index != 0) {
return;
}
previousPosition = null;
_this._offsetX = null;
_this._offsetY = null;
} else if (p.type === BABYLON2.PointerEventTypes.POINTERMOVE) {
if (!noPreventDefault) {
evt.preventDefault();
}
if (!previousPosition) {
return;
}
var index = _this._pointerPressed.indexOf(evt.pointerId);
if (index != 0) {
return;
}
_this._offsetX = evt.clientX - previousPosition.x;
_this._offsetY = -(evt.clientY - previousPosition.y);
}
};
}
this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON2.PointerEventTypes.POINTERDOWN | BABYLON2.PointerEventTypes.POINTERUP | BABYLON2.PointerEventTypes.POINTERMOVE);
if (this._onLostFocus) {
element.addEventListener("blur", this._onLostFocus);
}
};
FreeCameraTouchInput2.prototype.detachControl = function(element) {
if (this._pointerInput && element) {
if (this._observer) {
this.camera.getScene().onPointerObservable.remove(this._observer);
this._observer = null;
}
if (this._onLostFocus) {
element.removeEventListener("blur", this._onLostFocus);
this._onLostFocus = null;
}
this._pointerPressed = [];
this._offsetX = null;
this._offsetY = null;
}
};
FreeCameraTouchInput2.prototype.checkInputs = function() {
if (this._offsetX && this._offsetY) {
var camera2 = this.camera;
camera2.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
if (this._pointerPressed.length > 1) {
camera2.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
} else {
var speed = camera2._computeLocalCameraSpeed();
var direction = new BABYLON2.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
BABYLON2.Matrix.RotationYawPitchRollToRef(camera2.rotation.y, camera2.rotation.x, 0, camera2._cameraRotationMatrix);
camera2.cameraDirection.addInPlace(BABYLON2.Vector3.TransformCoordinates(direction, camera2._cameraRotationMatrix));
}
}
};
FreeCameraTouchInput2.prototype.getClassName = function() {
return "FreeCameraTouchInput";
};
FreeCameraTouchInput2.prototype.getSimpleName = function() {
return "touch";
};
__decorate([
BABYLON2.serialize()
], FreeCameraTouchInput2.prototype, "touchAngularSensibility", void 0);
__decorate([
BABYLON2.serialize()
], FreeCameraTouchInput2.prototype, "touchMoveSensibility", void 0);
return FreeCameraTouchInput2;
}()
);
BABYLON2.FreeCameraTouchInput = FreeCameraTouchInput;
BABYLON2.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("TouchCamera", function(name, scene) {
return function() {
return new TouchCamera(name, BABYLON2.Vector3.Zero(), scene);
};
});
var TouchCamera = (
/** @class */
function(_super) {
__extends(TouchCamera2, _super);
function TouchCamera2(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this.inputs.addTouch();
_this._setupInputs();
return _this;
}
Object.defineProperty(TouchCamera2.prototype, "touchAngularSensibility", {
/**
* Defines the touch sensibility for rotation.
* The higher the faster.
*/
get: function() {
var touch = this.inputs.attached["touch"];
if (touch) {
return touch.touchAngularSensibility;
}
return 0;
},
set: function(value) {
var touch = this.inputs.attached["touch"];
if (touch) {
touch.touchAngularSensibility = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(TouchCamera2.prototype, "touchMoveSensibility", {
/**
* Defines the touch sensibility for move.
* The higher the faster.
*/
get: function() {
var touch = this.inputs.attached["touch"];
if (touch) {
return touch.touchMoveSensibility;
}
return 0;
},
set: function(value) {
var touch = this.inputs.attached["touch"];
if (touch) {
touch.touchMoveSensibility = value;
}
},
enumerable: true,
configurable: true
});
TouchCamera2.prototype.getClassName = function() {
return "TouchCamera";
};
TouchCamera2.prototype._setupInputs = function() {
var mouse = this.inputs.attached["mouse"];
if (mouse) {
mouse.touchEnabled = false;
}
};
return TouchCamera2;
}(BABYLON2.FreeCamera)
);
BABYLON2.TouchCamera = TouchCamera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ProceduralTexture = (
/** @class */
function(_super) {
__extends(ProceduralTexture2, _super);
function ProceduralTexture2(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
if (fallbackTexture === void 0) {
fallbackTexture = null;
}
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (isCube === void 0) {
isCube = false;
}
var _this = _super.call(this, null, scene, !generateMipMaps) || this;
_this.isCube = isCube;
_this.isEnabled = true;
_this.autoClear = true;
_this.onGeneratedObservable = new BABYLON2.Observable();
_this._textures = {};
_this._currentRefreshId = -1;
_this._refreshRate = 1;
_this._vertexBuffers = {};
_this._uniforms = new Array();
_this._samplers = new Array();
_this._floats = {};
_this._ints = {};
_this._floatsArrays = {};
_this._colors3 = {};
_this._colors4 = {};
_this._vectors2 = {};
_this._vectors3 = {};
_this._matrices = {};
_this._fallbackTextureUsed = false;
_this._cachedDefines = "";
_this._contentUpdateId = -1;
scene = _this.getScene();
var component = scene._getComponent(BABYLON2.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
if (!component) {
component = new BABYLON2.ProceduralTextureSceneComponent(scene);
scene._addComponent(component);
}
scene.proceduralTextures.push(_this);
_this._engine = scene.getEngine();
_this.name = name;
_this.isRenderTarget = true;
_this._size = size;
_this._generateMipMaps = generateMipMaps;
_this.setFragment(fragment);
_this._fallbackTexture = fallbackTexture;
if (isCube) {
_this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
_this.setFloat("face", 0);
} else {
_this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
}
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
_this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = new BABYLON2.VertexBuffer(_this._engine, vertices, BABYLON2.VertexBuffer.PositionKind, false, false, 2);
_this._createIndexBuffer();
return _this;
}
ProceduralTexture2.prototype.getContent = function() {
if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
return this._contentData;
}
this._contentData = this.readPixels(0, 0, this._contentData);
this._contentUpdateId = this._currentRefreshId;
return this._contentData;
};
ProceduralTexture2.prototype._createIndexBuffer = function() {
var engine = this._engine;
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = engine.createIndexBuffer(indices);
};
ProceduralTexture2.prototype._rebuild = function() {
var vb = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vb) {
vb._rebuild();
}
this._createIndexBuffer();
if (this.refreshRate === BABYLON2.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
this.refreshRate = BABYLON2.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
}
};
ProceduralTexture2.prototype.reset = function() {
if (this._effect === void 0) {
return;
}
var engine = this._engine;
engine._releaseEffect(this._effect);
};
ProceduralTexture2.prototype._getDefines = function() {
return "";
};
ProceduralTexture2.prototype.isReady = function() {
var _this = this;
var engine = this._engine;
var shaders;
if (!this._fragment) {
return false;
}
if (this._fallbackTextureUsed) {
return true;
}
var defines = this._getDefines();
if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
return true;
}
if (this._fragment.fragmentElement !== void 0) {
shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
} else {
shaders = { vertex: "procedural", fragment: this._fragment };
}
this._cachedDefines = defines;
this._effect = engine.createEffect(shaders, [BABYLON2.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, void 0, void 0, function() {
_this.releaseInternalTexture();
if (_this._fallbackTexture) {
_this._texture = _this._fallbackTexture._texture;
if (_this._texture) {
_this._texture.incrementReferences();
}
}
_this._fallbackTextureUsed = true;
});
return this._effect.isReady();
};
ProceduralTexture2.prototype.resetRefreshCounter = function() {
this._currentRefreshId = -1;
};
ProceduralTexture2.prototype.setFragment = function(fragment) {
this._fragment = fragment;
};
Object.defineProperty(ProceduralTexture2.prototype, "refreshRate", {
/**
* Define the refresh rate of the texture or the rendering frequency.
* Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
*/
get: function() {
return this._refreshRate;
},
set: function(value) {
this._refreshRate = value;
this.resetRefreshCounter();
},
enumerable: true,
configurable: true
});
ProceduralTexture2.prototype._shouldRender = function() {
if (!this.isEnabled || !this.isReady() || !this._texture) {
if (this._texture) {
this._texture.isReady = false;
}
return false;
}
if (this._fallbackTextureUsed) {
return false;
}
if (this._currentRefreshId === -1) {
this._currentRefreshId = 1;
return true;
}
if (this.refreshRate === this._currentRefreshId) {
this._currentRefreshId = 1;
return true;
}
this._currentRefreshId++;
return false;
};
ProceduralTexture2.prototype.getRenderSize = function() {
return this._size;
};
ProceduralTexture2.prototype.resize = function(size, generateMipMaps) {
if (this._fallbackTextureUsed) {
return;
}
this.releaseInternalTexture();
this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
this._size = size;
this._generateMipMaps = generateMipMaps;
};
ProceduralTexture2.prototype._checkUniform = function(uniformName) {
if (this._uniforms.indexOf(uniformName) === -1) {
this._uniforms.push(uniformName);
}
};
ProceduralTexture2.prototype.setTexture = function(name, texture) {
if (this._samplers.indexOf(name) === -1) {
this._samplers.push(name);
}
this._textures[name] = texture;
return this;
};
ProceduralTexture2.prototype.setFloat = function(name, value) {
this._checkUniform(name);
this._floats[name] = value;
return this;
};
ProceduralTexture2.prototype.setInt = function(name, value) {
this._checkUniform(name);
this._ints[name] = value;
return this;
};
ProceduralTexture2.prototype.setFloats = function(name, value) {
this._checkUniform(name);
this._floatsArrays[name] = value;
return this;
};
ProceduralTexture2.prototype.setColor3 = function(name, value) {
this._checkUniform(name);
this._colors3[name] = value;
return this;
};
ProceduralTexture2.prototype.setColor4 = function(name, value) {
this._checkUniform(name);
this._colors4[name] = value;
return this;
};
ProceduralTexture2.prototype.setVector2 = function(name, value) {
this._checkUniform(name);
this._vectors2[name] = value;
return this;
};
ProceduralTexture2.prototype.setVector3 = function(name, value) {
this._checkUniform(name);
this._vectors3[name] = value;
return this;
};
ProceduralTexture2.prototype.setMatrix = function(name, value) {
this._checkUniform(name);
this._matrices[name] = value;
return this;
};
ProceduralTexture2.prototype.render = function(useCameraPostProcess) {
var scene = this.getScene();
if (!scene) {
return;
}
var engine = this._engine;
engine.enableEffect(this._effect);
engine.setState(false);
for (var name in this._textures) {
this._effect.setTexture(name, this._textures[name]);
}
for (name in this._ints) {
this._effect.setInt(name, this._ints[name]);
}
for (name in this._floats) {
this._effect.setFloat(name, this._floats[name]);
}
for (name in this._floatsArrays) {
this._effect.setArray(name, this._floatsArrays[name]);
}
for (name in this._colors3) {
this._effect.setColor3(name, this._colors3[name]);
}
for (name in this._colors4) {
var color = this._colors4[name];
this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
}
for (name in this._vectors2) {
this._effect.setVector2(name, this._vectors2[name]);
}
for (name in this._vectors3) {
this._effect.setVector3(name, this._vectors3[name]);
}
for (name in this._matrices) {
this._effect.setMatrix(name, this._matrices[name]);
}
if (!this._texture) {
return;
}
if (this.isCube) {
for (var face = 0; face < 6; face++) {
engine.bindFramebuffer(this._texture, face, void 0, void 0, true);
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
this._effect.setFloat("face", face);
if (this.autoClear) {
engine.clear(scene.clearColor, true, false, false);
}
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
if (face === 5) {
engine.generateMipMapsForCubemap(this._texture);
}
}
} else {
engine.bindFramebuffer(this._texture, 0, void 0, void 0, true);
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
if (this.autoClear) {
engine.clear(scene.clearColor, true, false, false);
}
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
}
engine.unBindFramebuffer(this._texture, this.isCube);
if (this.onGenerated) {
this.onGenerated();
}
this.onGeneratedObservable.notifyObservers(this);
};
ProceduralTexture2.prototype.clone = function() {
var textureSize = this.getSize();
var newTexture = new ProceduralTexture2(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
newTexture.hasAlpha = this.hasAlpha;
newTexture.level = this.level;
newTexture.coordinatesMode = this.coordinatesMode;
return newTexture;
};
ProceduralTexture2.prototype.dispose = function() {
var scene = this.getScene();
if (!scene) {
return;
}
var index = scene.proceduralTextures.indexOf(this);
if (index >= 0) {
scene.proceduralTextures.splice(index, 1);
}
var vertexBuffer = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = null;
}
if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
this._indexBuffer = null;
}
_super.prototype.dispose.call(this);
};
__decorate([
BABYLON2.serialize()
], ProceduralTexture2.prototype, "isEnabled", void 0);
__decorate([
BABYLON2.serialize()
], ProceduralTexture2.prototype, "autoClear", void 0);
__decorate([
BABYLON2.serialize()
], ProceduralTexture2.prototype, "_generateMipMaps", void 0);
__decorate([
BABYLON2.serialize()
], ProceduralTexture2.prototype, "_size", void 0);
__decorate([
BABYLON2.serialize()
], ProceduralTexture2.prototype, "refreshRate", null);
return ProceduralTexture2;
}(BABYLON2.Texture)
);
BABYLON2.ProceduralTexture = ProceduralTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ProceduralTextureSceneComponent = (
/** @class */
function() {
function ProceduralTextureSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
this.scene = scene;
this.scene.proceduralTextures = new Array();
scene.layers = new Array();
}
ProceduralTextureSceneComponent2.prototype.register = function() {
this.scene._beforeClearStage.registerStep(BABYLON2.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
};
ProceduralTextureSceneComponent2.prototype.rebuild = function() {
};
ProceduralTextureSceneComponent2.prototype.dispose = function() {
};
ProceduralTextureSceneComponent2.prototype._beforeClear = function() {
if (this.scene.proceduralTexturesEnabled) {
BABYLON2.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
if (proceduralTexture._shouldRender()) {
proceduralTexture.render();
}
}
BABYLON2.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
}
};
return ProceduralTextureSceneComponent2;
}()
);
BABYLON2.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var CustomProceduralTexture = (
/** @class */
function(_super) {
__extends(CustomProceduralTexture2, _super);
function CustomProceduralTexture2(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
_this._animate = true;
_this._time = 0;
_this._texturePath = texturePath;
_this._loadJson(texturePath);
_this.refreshRate = 1;
return _this;
}
CustomProceduralTexture2.prototype._loadJson = function(jsonUrl) {
var _this = this;
var noConfigFile = function() {
BABYLON2.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
try {
_this.setFragment(_this._texturePath);
} catch (ex) {
BABYLON2.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
}
};
var configFileUrl = jsonUrl + "/config.json";
var xhr = new XMLHttpRequest();
xhr.open("GET", configFileUrl, true);
xhr.addEventListener("load", function() {
if (xhr.status === 200 || BABYLON2.Tools.ValidateXHRData(xhr, 1)) {
try {
_this._config = JSON.parse(xhr.response);
_this.updateShaderUniforms();
_this.updateTextures();
_this.setFragment(_this._texturePath + "/custom");
_this._animate = _this._config.animate;
_this.refreshRate = _this._config.refreshrate;
} catch (ex) {
noConfigFile();
}
} else {
noConfigFile();
}
}, false);
xhr.addEventListener("error", function() {
noConfigFile();
}, false);
try {
xhr.send();
} catch (ex) {
BABYLON2.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
}
};
CustomProceduralTexture2.prototype.isReady = function() {
if (!_super.prototype.isReady.call(this)) {
return false;
}
for (var name in this._textures) {
var texture = this._textures[name];
if (!texture.isReady()) {
return false;
}
}
return true;
};
CustomProceduralTexture2.prototype.render = function(useCameraPostProcess) {
var scene = this.getScene();
if (this._animate && scene) {
this._time += scene.getAnimationRatio() * 0.03;
this.updateShaderUniforms();
}
_super.prototype.render.call(this, useCameraPostProcess);
};
CustomProceduralTexture2.prototype.updateTextures = function() {
for (var i2 = 0; i2 < this._config.sampler2Ds.length; i2++) {
this.setTexture(this._config.sampler2Ds[i2].sample2Dname, new BABYLON2.Texture(this._texturePath + "/" + this._config.sampler2Ds[i2].textureRelativeUrl, this.getScene()));
}
};
CustomProceduralTexture2.prototype.updateShaderUniforms = function() {
if (this._config) {
for (var j = 0; j < this._config.uniforms.length; j++) {
var uniform = this._config.uniforms[j];
switch (uniform.type) {
case "float":
this.setFloat(uniform.name, uniform.value);
break;
case "color3":
this.setColor3(uniform.name, new BABYLON2.Color3(uniform.r, uniform.g, uniform.b));
break;
case "color4":
this.setColor4(uniform.name, new BABYLON2.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
break;
case "vector2":
this.setVector2(uniform.name, new BABYLON2.Vector2(uniform.x, uniform.y));
break;
case "vector3":
this.setVector3(uniform.name, new BABYLON2.Vector3(uniform.x, uniform.y, uniform.z));
break;
}
}
}
this.setFloat("time", this._time);
};
Object.defineProperty(CustomProceduralTexture2.prototype, "animate", {
/**
* Define if the texture animates or not.
*/
get: function() {
return this._animate;
},
set: function(value) {
this._animate = value;
},
enumerable: true,
configurable: true
});
return CustomProceduralTexture2;
}(BABYLON2.ProceduralTexture)
);
BABYLON2.CustomProceduralTexture = CustomProceduralTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FreeCameraGamepadInput = (
/** @class */
function() {
function FreeCameraGamepadInput2() {
this.gamepadAngularSensibility = 200;
this.gamepadMoveSensibility = 40;
this._cameraTransform = BABYLON2.Matrix.Identity();
this._deltaTransform = BABYLON2.Vector3.Zero();
this._vector3 = BABYLON2.Vector3.Zero();
this._vector2 = BABYLON2.Vector2.Zero();
}
FreeCameraGamepadInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
var manager = this.camera.getScene().gamepadManager;
this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function(gamepad) {
if (gamepad.type !== BABYLON2.Gamepad.POSE_ENABLED) {
if (!_this.gamepad || gamepad.type === BABYLON2.Gamepad.XBOX) {
_this.gamepad = gamepad;
}
}
});
this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function(gamepad) {
if (_this.gamepad === gamepad) {
_this.gamepad = null;
}
});
this.gamepad = manager.getGamepadByType(BABYLON2.Gamepad.XBOX);
};
FreeCameraGamepadInput2.prototype.detachControl = function(element) {
this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
this.gamepad = null;
};
FreeCameraGamepadInput2.prototype.checkInputs = function() {
if (this.gamepad && this.gamepad.leftStick) {
var camera2 = this.camera;
var LSValues = this.gamepad.leftStick;
var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
LSValues.x = Math.abs(normalizedLX) > 5e-3 ? 0 + normalizedLX : 0;
LSValues.y = Math.abs(normalizedLY) > 5e-3 ? 0 + normalizedLY : 0;
var RSValues = this.gamepad.rightStick;
if (RSValues) {
var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
RSValues.x = Math.abs(normalizedRX) > 1e-3 ? 0 + normalizedRX : 0;
RSValues.y = Math.abs(normalizedRY) > 1e-3 ? 0 + normalizedRY : 0;
} else {
RSValues = { x: 0, y: 0 };
}
if (!camera2.rotationQuaternion) {
BABYLON2.Matrix.RotationYawPitchRollToRef(camera2.rotation.y, camera2.rotation.x, 0, this._cameraTransform);
} else {
camera2.rotationQuaternion.toRotationMatrix(this._cameraTransform);
}
var speed = camera2._computeLocalCameraSpeed() * 50;
this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
BABYLON2.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
camera2.cameraDirection.addInPlace(this._deltaTransform);
this._vector2.copyFromFloats(RSValues.y, RSValues.x);
camera2.cameraRotation.addInPlace(this._vector2);
}
};
FreeCameraGamepadInput2.prototype.getClassName = function() {
return "FreeCameraGamepadInput";
};
FreeCameraGamepadInput2.prototype.getSimpleName = function() {
return "gamepad";
};
__decorate([
BABYLON2.serialize()
], FreeCameraGamepadInput2.prototype, "gamepadAngularSensibility", void 0);
__decorate([
BABYLON2.serialize()
], FreeCameraGamepadInput2.prototype, "gamepadMoveSensibility", void 0);
return FreeCameraGamepadInput2;
}()
);
BABYLON2.FreeCameraGamepadInput = FreeCameraGamepadInput;
BABYLON2.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ArcRotateCameraGamepadInput = (
/** @class */
function() {
function ArcRotateCameraGamepadInput2() {
this.gamepadRotationSensibility = 80;
this.gamepadMoveSensibility = 40;
}
ArcRotateCameraGamepadInput2.prototype.attachControl = function(element, noPreventDefault) {
var _this = this;
var manager = this.camera.getScene().gamepadManager;
this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function(gamepad) {
if (gamepad.type !== BABYLON2.Gamepad.POSE_ENABLED) {
if (!_this.gamepad || gamepad.type === BABYLON2.Gamepad.XBOX) {
_this.gamepad = gamepad;
}
}
});
this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function(gamepad) {
if (_this.gamepad === gamepad) {
_this.gamepad = null;
}
});
this.gamepad = manager.getGamepadByType(BABYLON2.Gamepad.XBOX);
};
ArcRotateCameraGamepadInput2.prototype.detachControl = function(element) {
this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
this.gamepad = null;
};
ArcRotateCameraGamepadInput2.prototype.checkInputs = function() {
if (this.gamepad) {
var camera2 = this.camera;
var RSValues = this.gamepad.rightStick;
if (RSValues) {
if (RSValues.x != 0) {
var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
if (normalizedRX != 0 && Math.abs(normalizedRX) > 5e-3) {
camera2.inertialAlphaOffset += normalizedRX;
}
}
if (RSValues.y != 0) {
var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
if (normalizedRY != 0 && Math.abs(normalizedRY) > 5e-3) {
camera2.inertialBetaOffset += normalizedRY;
}
}
}
var LSValues = this.gamepad.leftStick;
if (LSValues && LSValues.y != 0) {
var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
if (normalizedLY != 0 && Math.abs(normalizedLY) > 5e-3) {
this.camera.inertialRadiusOffset -= normalizedLY;
}
}
}
};
ArcRotateCameraGamepadInput2.prototype.getClassName = function() {
return "ArcRotateCameraGamepadInput";
};
ArcRotateCameraGamepadInput2.prototype.getSimpleName = function() {
return "gamepad";
};
__decorate([
BABYLON2.serialize()
], ArcRotateCameraGamepadInput2.prototype, "gamepadRotationSensibility", void 0);
__decorate([
BABYLON2.serialize()
], ArcRotateCameraGamepadInput2.prototype, "gamepadMoveSensibility", void 0);
return ArcRotateCameraGamepadInput2;
}()
);
BABYLON2.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
BABYLON2.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var GamepadManager = (
/** @class */
function() {
function GamepadManager2(_scene) {
var _this = this;
this._scene = _scene;
this._babylonGamepads = [];
this._oneGamepadConnected = false;
this._isMonitoring = false;
this.onGamepadDisconnectedObservable = new BABYLON2.Observable();
if (!BABYLON2.Tools.IsWindowObjectExist()) {
this._gamepadEventSupported = false;
} else {
this._gamepadEventSupported = "GamepadEvent" in window;
this._gamepadSupport = navigator.getGamepads || navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads;
}
this.onGamepadConnectedObservable = new BABYLON2.Observable(function(observer2) {
for (var i2 in _this._babylonGamepads) {
var gamepad = _this._babylonGamepads[i2];
if (gamepad && gamepad._isConnected) {
_this.onGamepadConnectedObservable.notifyObserver(observer2, gamepad);
}
}
});
this._onGamepadConnectedEvent = function(evt) {
var gamepad = evt.gamepad;
if (gamepad.index in _this._babylonGamepads) {
if (_this._babylonGamepads[gamepad.index].isConnected) {
return;
}
}
var newGamepad;
if (_this._babylonGamepads[gamepad.index]) {
newGamepad = _this._babylonGamepads[gamepad.index];
newGamepad.browserGamepad = gamepad;
newGamepad._isConnected = true;
} else {
newGamepad = _this._addNewGamepad(gamepad);
}
_this.onGamepadConnectedObservable.notifyObservers(newGamepad);
_this._startMonitoringGamepads();
};
this._onGamepadDisconnectedEvent = function(evt) {
var gamepad = evt.gamepad;
for (var i2 in _this._babylonGamepads) {
if (_this._babylonGamepads[i2].index === gamepad.index) {
var disconnectedGamepad = _this._babylonGamepads[i2];
disconnectedGamepad._isConnected = false;
_this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
break;
}
}
};
if (this._gamepadSupport) {
this._updateGamepadObjects();
if (this._babylonGamepads.length) {
this._startMonitoringGamepads();
}
if (this._gamepadEventSupported) {
window.addEventListener("gamepadconnected", this._onGamepadConnectedEvent, false);
window.addEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent, false);
} else {
this._startMonitoringGamepads();
}
}
}
Object.defineProperty(GamepadManager2.prototype, "gamepads", {
/**
* The gamepads in the game pad manager
*/
get: function() {
return this._babylonGamepads;
},
enumerable: true,
configurable: true
});
GamepadManager2.prototype.getGamepadByType = function(type) {
if (type === void 0) {
type = BABYLON2.Gamepad.XBOX;
}
for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
var gamepad = _a[_i];
if (gamepad && gamepad.type === type) {
return gamepad;
}
}
return null;
};
GamepadManager2.prototype.dispose = function() {
if (this._gamepadEventSupported) {
if (this._onGamepadConnectedEvent) {
window.removeEventListener("gamepadconnected", this._onGamepadConnectedEvent);
}
if (this._onGamepadDisconnectedEvent) {
window.removeEventListener("gamepaddisconnected", this._onGamepadDisconnectedEvent);
}
this._onGamepadConnectedEvent = null;
this._onGamepadDisconnectedEvent = null;
}
this._babylonGamepads.forEach(function(gamepad) {
gamepad.dispose();
});
this.onGamepadConnectedObservable.clear();
this.onGamepadDisconnectedObservable.clear();
this._oneGamepadConnected = false;
this._stopMonitoringGamepads();
this._babylonGamepads = [];
};
GamepadManager2.prototype._addNewGamepad = function(gamepad) {
if (!this._oneGamepadConnected) {
this._oneGamepadConnected = true;
}
var newGamepad;
var xboxOne = gamepad.id.search("Xbox One") !== -1;
if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
newGamepad = new BABYLON2.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
} else if (gamepad.pose) {
newGamepad = BABYLON2.PoseEnabledControllerHelper.InitiateController(gamepad);
} else {
newGamepad = new BABYLON2.GenericPad(gamepad.id, gamepad.index, gamepad);
}
this._babylonGamepads[newGamepad.index] = newGamepad;
return newGamepad;
};
GamepadManager2.prototype._startMonitoringGamepads = function() {
if (!this._isMonitoring) {
this._isMonitoring = true;
if (!this._scene) {
this._checkGamepadsStatus();
}
}
};
GamepadManager2.prototype._stopMonitoringGamepads = function() {
this._isMonitoring = false;
};
GamepadManager2.prototype._checkGamepadsStatus = function() {
var _this = this;
this._updateGamepadObjects();
for (var i2 in this._babylonGamepads) {
var gamepad = this._babylonGamepads[i2];
if (!gamepad || !gamepad.isConnected) {
continue;
}
gamepad.update();
}
if (this._isMonitoring && !this._scene) {
BABYLON2.Tools.QueueNewFrame(function() {
_this._checkGamepadsStatus();
});
}
};
GamepadManager2.prototype._updateGamepadObjects = function() {
var gamepads = navigator.getGamepads ? navigator.getGamepads() : navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : [];
for (var i2 = 0; i2 < gamepads.length; i2++) {
var gamepad = gamepads[i2];
if (gamepad) {
if (!this._babylonGamepads[gamepad.index]) {
var newGamepad = this._addNewGamepad(gamepad);
this.onGamepadConnectedObservable.notifyObservers(newGamepad);
} else {
this._babylonGamepads[i2].browserGamepad = gamepad;
if (!this._babylonGamepads[i2].isConnected) {
this._babylonGamepads[i2]._isConnected = true;
this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i2]);
}
}
}
}
};
return GamepadManager2;
}()
);
BABYLON2.GamepadManager = GamepadManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var StickValues = (
/** @class */
function() {
function StickValues2(x, y) {
this.x = x;
this.y = y;
}
return StickValues2;
}()
);
BABYLON2.StickValues = StickValues;
var Gamepad2 = (
/** @class */
function() {
function Gamepad3(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
if (leftStickX === void 0) {
leftStickX = 0;
}
if (leftStickY === void 0) {
leftStickY = 1;
}
if (rightStickX === void 0) {
rightStickX = 2;
}
if (rightStickY === void 0) {
rightStickY = 3;
}
this.id = id;
this.index = index;
this.browserGamepad = browserGamepad;
this._leftStick = { x: 0, y: 0 };
this._rightStick = { x: 0, y: 0 };
this._isConnected = true;
this._invertLeftStickY = false;
this.type = Gamepad3.GAMEPAD;
this._leftStickAxisX = leftStickX;
this._leftStickAxisY = leftStickY;
this._rightStickAxisX = rightStickX;
this._rightStickAxisY = rightStickY;
if (this.browserGamepad.axes.length >= 2) {
this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
}
if (this.browserGamepad.axes.length >= 4) {
this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
}
}
Object.defineProperty(Gamepad3.prototype, "isConnected", {
/**
* Specifies if the gamepad has been connected
*/
get: function() {
return this._isConnected;
},
enumerable: true,
configurable: true
});
Gamepad3.prototype.onleftstickchanged = function(callback) {
this._onleftstickchanged = callback;
};
Gamepad3.prototype.onrightstickchanged = function(callback) {
this._onrightstickchanged = callback;
};
Object.defineProperty(Gamepad3.prototype, "leftStick", {
/**
* Gets the left joystick
*/
get: function() {
return this._leftStick;
},
/**
* Sets the left joystick values
*/
set: function(newValues) {
if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
this._onleftstickchanged(newValues);
}
this._leftStick = newValues;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Gamepad3.prototype, "rightStick", {
/**
* Gets the right joystick
*/
get: function() {
return this._rightStick;
},
/**
* Sets the right joystick value
*/
set: function(newValues) {
if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
this._onrightstickchanged(newValues);
}
this._rightStick = newValues;
},
enumerable: true,
configurable: true
});
Gamepad3.prototype.update = function() {
if (this._leftStick) {
this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
if (this._invertLeftStickY) {
this.leftStick.y *= -1;
}
}
if (this._rightStick) {
this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
}
};
Gamepad3.prototype.dispose = function() {
};
Gamepad3.GAMEPAD = 0;
Gamepad3.GENERIC = 1;
Gamepad3.XBOX = 2;
Gamepad3.POSE_ENABLED = 3;
return Gamepad3;
}()
);
BABYLON2.Gamepad = Gamepad2;
var GenericPad = (
/** @class */
function(_super) {
__extends(GenericPad2, _super);
function GenericPad2(id, index, browserGamepad) {
var _this = _super.call(this, id, index, browserGamepad) || this;
_this.onButtonDownObservable = new BABYLON2.Observable();
_this.onButtonUpObservable = new BABYLON2.Observable();
_this.type = Gamepad2.GENERIC;
_this._buttons = new Array(browserGamepad.buttons.length);
return _this;
}
GenericPad2.prototype.onbuttondown = function(callback) {
this._onbuttondown = callback;
};
GenericPad2.prototype.onbuttonup = function(callback) {
this._onbuttonup = callback;
};
GenericPad2.prototype._setButtonValue = function(newValue, currentValue, buttonIndex) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._onbuttondown) {
this._onbuttondown(buttonIndex);
}
this.onButtonDownObservable.notifyObservers(buttonIndex);
}
if (newValue === 0) {
if (this._onbuttonup) {
this._onbuttonup(buttonIndex);
}
this.onButtonUpObservable.notifyObservers(buttonIndex);
}
}
return newValue;
};
GenericPad2.prototype.update = function() {
_super.prototype.update.call(this);
for (var index = 0; index < this._buttons.length; index++) {
this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
}
};
GenericPad2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
this.onButtonDownObservable.clear();
this.onButtonUpObservable.clear();
};
return GenericPad2;
}(Gamepad2)
);
BABYLON2.GenericPad = GenericPad;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Xbox360Button;
(function(Xbox360Button2) {
Xbox360Button2[Xbox360Button2["A"] = 0] = "A";
Xbox360Button2[Xbox360Button2["B"] = 1] = "B";
Xbox360Button2[Xbox360Button2["X"] = 2] = "X";
Xbox360Button2[Xbox360Button2["Y"] = 3] = "Y";
Xbox360Button2[Xbox360Button2["Start"] = 4] = "Start";
Xbox360Button2[Xbox360Button2["Back"] = 5] = "Back";
Xbox360Button2[Xbox360Button2["LB"] = 6] = "LB";
Xbox360Button2[Xbox360Button2["RB"] = 7] = "RB";
Xbox360Button2[Xbox360Button2["LeftStick"] = 8] = "LeftStick";
Xbox360Button2[Xbox360Button2["RightStick"] = 9] = "RightStick";
})(Xbox360Button = BABYLON2.Xbox360Button || (BABYLON2.Xbox360Button = {}));
var Xbox360Dpad;
(function(Xbox360Dpad2) {
Xbox360Dpad2[Xbox360Dpad2["Up"] = 0] = "Up";
Xbox360Dpad2[Xbox360Dpad2["Down"] = 1] = "Down";
Xbox360Dpad2[Xbox360Dpad2["Left"] = 2] = "Left";
Xbox360Dpad2[Xbox360Dpad2["Right"] = 3] = "Right";
})(Xbox360Dpad = BABYLON2.Xbox360Dpad || (BABYLON2.Xbox360Dpad = {}));
var Xbox360Pad = (
/** @class */
function(_super) {
__extends(Xbox360Pad2, _super);
function Xbox360Pad2(id, index, gamepad, xboxOne) {
if (xboxOne === void 0) {
xboxOne = false;
}
var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
_this._leftTrigger = 0;
_this._rightTrigger = 0;
_this.onButtonDownObservable = new BABYLON2.Observable();
_this.onButtonUpObservable = new BABYLON2.Observable();
_this.onPadDownObservable = new BABYLON2.Observable();
_this.onPadUpObservable = new BABYLON2.Observable();
_this._buttonA = 0;
_this._buttonB = 0;
_this._buttonX = 0;
_this._buttonY = 0;
_this._buttonBack = 0;
_this._buttonStart = 0;
_this._buttonLB = 0;
_this._buttonRB = 0;
_this._buttonLeftStick = 0;
_this._buttonRightStick = 0;
_this._dPadUp = 0;
_this._dPadDown = 0;
_this._dPadLeft = 0;
_this._dPadRight = 0;
_this._isXboxOnePad = false;
_this.type = BABYLON2.Gamepad.XBOX;
_this._isXboxOnePad = xboxOne;
return _this;
}
Xbox360Pad2.prototype.onlefttriggerchanged = function(callback) {
this._onlefttriggerchanged = callback;
};
Xbox360Pad2.prototype.onrighttriggerchanged = function(callback) {
this._onrighttriggerchanged = callback;
};
Object.defineProperty(Xbox360Pad2.prototype, "leftTrigger", {
/**
* Gets the left trigger value
*/
get: function() {
return this._leftTrigger;
},
/**
* Sets the left trigger value
*/
set: function(newValue) {
if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
this._onlefttriggerchanged(newValue);
}
this._leftTrigger = newValue;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "rightTrigger", {
/**
* Gets the right trigger value
*/
get: function() {
return this._rightTrigger;
},
/**
* Sets the right trigger value
*/
set: function(newValue) {
if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
this._onrighttriggerchanged(newValue);
}
this._rightTrigger = newValue;
},
enumerable: true,
configurable: true
});
Xbox360Pad2.prototype.onbuttondown = function(callback) {
this._onbuttondown = callback;
};
Xbox360Pad2.prototype.onbuttonup = function(callback) {
this._onbuttonup = callback;
};
Xbox360Pad2.prototype.ondpaddown = function(callback) {
this._ondpaddown = callback;
};
Xbox360Pad2.prototype.ondpadup = function(callback) {
this._ondpadup = callback;
};
Xbox360Pad2.prototype._setButtonValue = function(newValue, currentValue, buttonType) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._onbuttondown) {
this._onbuttondown(buttonType);
}
this.onButtonDownObservable.notifyObservers(buttonType);
}
if (newValue === 0) {
if (this._onbuttonup) {
this._onbuttonup(buttonType);
}
this.onButtonUpObservable.notifyObservers(buttonType);
}
}
return newValue;
};
Xbox360Pad2.prototype._setDPadValue = function(newValue, currentValue, buttonType) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._ondpaddown) {
this._ondpaddown(buttonType);
}
this.onPadDownObservable.notifyObservers(buttonType);
}
if (newValue === 0) {
if (this._ondpadup) {
this._ondpadup(buttonType);
}
this.onPadUpObservable.notifyObservers(buttonType);
}
}
return newValue;
};
Object.defineProperty(Xbox360Pad2.prototype, "buttonA", {
/**
* Gets the value of the `A` button
*/
get: function() {
return this._buttonA;
},
/**
* Sets the value of the `A` button
*/
set: function(value) {
this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonB", {
/**
* Gets the value of the `B` button
*/
get: function() {
return this._buttonB;
},
/**
* Sets the value of the `B` button
*/
set: function(value) {
this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonX", {
/**
* Gets the value of the `X` button
*/
get: function() {
return this._buttonX;
},
/**
* Sets the value of the `X` button
*/
set: function(value) {
this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonY", {
/**
* Gets the value of the `Y` button
*/
get: function() {
return this._buttonY;
},
/**
* Sets the value of the `Y` button
*/
set: function(value) {
this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonStart", {
/**
* Gets the value of the `Start` button
*/
get: function() {
return this._buttonStart;
},
/**
* Sets the value of the `Start` button
*/
set: function(value) {
this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonBack", {
/**
* Gets the value of the `Back` button
*/
get: function() {
return this._buttonBack;
},
/**
* Sets the value of the `Back` button
*/
set: function(value) {
this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonLB", {
/**
* Gets the value of the `Left` button
*/
get: function() {
return this._buttonLB;
},
/**
* Sets the value of the `Left` button
*/
set: function(value) {
this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonRB", {
/**
* Gets the value of the `Right` button
*/
get: function() {
return this._buttonRB;
},
/**
* Sets the value of the `Right` button
*/
set: function(value) {
this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonLeftStick", {
/**
* Gets the value of the Left joystick
*/
get: function() {
return this._buttonLeftStick;
},
/**
* Sets the value of the Left joystick
*/
set: function(value) {
this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "buttonRightStick", {
/**
* Gets the value of the Right joystick
*/
get: function() {
return this._buttonRightStick;
},
/**
* Sets the value of the Right joystick
*/
set: function(value) {
this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "dPadUp", {
/**
* Gets the value of D-pad up
*/
get: function() {
return this._dPadUp;
},
/**
* Sets the value of D-pad up
*/
set: function(value) {
this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "dPadDown", {
/**
* Gets the value of D-pad down
*/
get: function() {
return this._dPadDown;
},
/**
* Sets the value of D-pad down
*/
set: function(value) {
this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "dPadLeft", {
/**
* Gets the value of D-pad left
*/
get: function() {
return this._dPadLeft;
},
/**
* Sets the value of D-pad left
*/
set: function(value) {
this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Xbox360Pad2.prototype, "dPadRight", {
/**
* Gets the value of D-pad right
*/
get: function() {
return this._dPadRight;
},
/**
* Sets the value of D-pad right
*/
set: function(value) {
this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
},
enumerable: true,
configurable: true
});
Xbox360Pad2.prototype.update = function() {
_super.prototype.update.call(this);
if (this._isXboxOnePad) {
this.buttonA = this.browserGamepad.buttons[0].value;
this.buttonB = this.browserGamepad.buttons[1].value;
this.buttonX = this.browserGamepad.buttons[2].value;
this.buttonY = this.browserGamepad.buttons[3].value;
this.buttonLB = this.browserGamepad.buttons[4].value;
this.buttonRB = this.browserGamepad.buttons[5].value;
this.leftTrigger = this.browserGamepad.axes[2];
this.rightTrigger = this.browserGamepad.axes[5];
this.buttonBack = this.browserGamepad.buttons[9].value;
this.buttonStart = this.browserGamepad.buttons[8].value;
this.buttonLeftStick = this.browserGamepad.buttons[6].value;
this.buttonRightStick = this.browserGamepad.buttons[7].value;
this.dPadUp = this.browserGamepad.buttons[11].value;
this.dPadDown = this.browserGamepad.buttons[12].value;
this.dPadLeft = this.browserGamepad.buttons[13].value;
this.dPadRight = this.browserGamepad.buttons[14].value;
} else {
this.buttonA = this.browserGamepad.buttons[0].value;
this.buttonB = this.browserGamepad.buttons[1].value;
this.buttonX = this.browserGamepad.buttons[2].value;
this.buttonY = this.browserGamepad.buttons[3].value;
this.buttonLB = this.browserGamepad.buttons[4].value;
this.buttonRB = this.browserGamepad.buttons[5].value;
this.leftTrigger = this.browserGamepad.buttons[6].value;
this.rightTrigger = this.browserGamepad.buttons[7].value;
this.buttonBack = this.browserGamepad.buttons[8].value;
this.buttonStart = this.browserGamepad.buttons[9].value;
this.buttonLeftStick = this.browserGamepad.buttons[10].value;
this.buttonRightStick = this.browserGamepad.buttons[11].value;
this.dPadUp = this.browserGamepad.buttons[12].value;
this.dPadDown = this.browserGamepad.buttons[13].value;
this.dPadLeft = this.browserGamepad.buttons[14].value;
this.dPadRight = this.browserGamepad.buttons[15].value;
}
};
Xbox360Pad2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
this.onButtonDownObservable.clear();
this.onButtonUpObservable.clear();
this.onPadDownObservable.clear();
this.onPadUpObservable.clear();
};
return Xbox360Pad2;
}(BABYLON2.Gamepad)
);
BABYLON2.Xbox360Pad = Xbox360Pad;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PoseEnabledControllerType;
(function(PoseEnabledControllerType2) {
PoseEnabledControllerType2[PoseEnabledControllerType2["VIVE"] = 0] = "VIVE";
PoseEnabledControllerType2[PoseEnabledControllerType2["OCULUS"] = 1] = "OCULUS";
PoseEnabledControllerType2[PoseEnabledControllerType2["WINDOWS"] = 2] = "WINDOWS";
PoseEnabledControllerType2[PoseEnabledControllerType2["GEAR_VR"] = 3] = "GEAR_VR";
PoseEnabledControllerType2[PoseEnabledControllerType2["DAYDREAM"] = 4] = "DAYDREAM";
PoseEnabledControllerType2[PoseEnabledControllerType2["GENERIC"] = 5] = "GENERIC";
})(PoseEnabledControllerType = BABYLON2.PoseEnabledControllerType || (BABYLON2.PoseEnabledControllerType = {}));
var PoseEnabledControllerHelper = (
/** @class */
function() {
function PoseEnabledControllerHelper2() {
}
PoseEnabledControllerHelper2.InitiateController = function(vrGamepad) {
if (vrGamepad.id.indexOf("Oculus Touch") !== -1) {
return new BABYLON2.OculusTouchController(vrGamepad);
} else if (vrGamepad.id.indexOf(BABYLON2.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
return new BABYLON2.WindowsMotionController(vrGamepad);
} else if (vrGamepad.id.toLowerCase().indexOf("openvr") !== -1) {
return new BABYLON2.ViveController(vrGamepad);
} else if (vrGamepad.id.indexOf(BABYLON2.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf("Oculus Go") !== -1) {
return new BABYLON2.GearVRController(vrGamepad);
} else if (vrGamepad.id.indexOf(BABYLON2.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
return new BABYLON2.DaydreamController(vrGamepad);
} else {
return new BABYLON2.GenericController(vrGamepad);
}
};
return PoseEnabledControllerHelper2;
}()
);
BABYLON2.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
var PoseEnabledController = (
/** @class */
function(_super) {
__extends(PoseEnabledController2, _super);
function PoseEnabledController2(browserGamepad) {
var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
_this._deviceRoomPosition = BABYLON2.Vector3.Zero();
_this._deviceRoomRotationQuaternion = new BABYLON2.Quaternion();
_this.devicePosition = BABYLON2.Vector3.Zero();
_this.deviceRotationQuaternion = new BABYLON2.Quaternion();
_this.deviceScaleFactor = 1;
_this._trackPosition = true;
_this._maxRotationDistFromHeadset = Math.PI / 5;
_this._draggedRoomRotation = 0;
_this._leftHandSystemQuaternion = new BABYLON2.Quaternion();
_this._deviceToWorld = BABYLON2.Matrix.Identity();
_this._pointingPoseNode = null;
_this._workingMatrix = BABYLON2.Matrix.Identity();
_this._meshAttachedObservable = new BABYLON2.Observable();
_this.type = BABYLON2.Gamepad.POSE_ENABLED;
_this.controllerType = PoseEnabledControllerType.GENERIC;
_this.position = BABYLON2.Vector3.Zero();
_this.rotationQuaternion = new BABYLON2.Quaternion();
_this._calculatedPosition = BABYLON2.Vector3.Zero();
_this._calculatedRotation = new BABYLON2.Quaternion();
BABYLON2.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
return _this;
}
PoseEnabledController2.prototype._disableTrackPosition = function(fixedPosition) {
if (this._trackPosition) {
this._calculatedPosition.copyFrom(fixedPosition);
this._trackPosition = false;
}
};
PoseEnabledController2.prototype.update = function() {
_super.prototype.update.call(this);
this._updatePoseAndMesh();
};
PoseEnabledController2.prototype._updatePoseAndMesh = function() {
var pose = this.browserGamepad.pose;
this.updateFromDevice(pose);
if (!this._trackPosition && BABYLON2.Engine.LastCreatedScene && BABYLON2.Engine.LastCreatedScene.activeCamera && BABYLON2.Engine.LastCreatedScene.activeCamera.devicePosition) {
var camera2 = BABYLON2.Engine.LastCreatedScene.activeCamera;
camera2._computeDevicePosition();
this._deviceToWorld.setTranslation(camera2.devicePosition);
if (camera2.deviceRotationQuaternion) {
var camera2 = camera2;
camera2._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON2.Tmp.Vector3[0]);
var distanceAway = Math.atan2(Math.sin(BABYLON2.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON2.Tmp.Vector3[0].y - this._draggedRoomRotation));
if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
this._draggedRoomRotation += rotationAmount;
var sin = Math.sin(-rotationAmount);
var cos = Math.cos(-rotationAmount);
this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
}
}
}
BABYLON2.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
BABYLON2.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
if (this._mesh) {
this._mesh.position.copyFrom(this.devicePosition);
if (this._mesh.rotationQuaternion) {
this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
}
}
};
PoseEnabledController2.prototype.updateFromDevice = function(poseData) {
if (poseData) {
this.rawPose = poseData;
if (poseData.position) {
this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
this._deviceRoomPosition.z *= -1;
}
if (this._trackPosition) {
this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
}
this._calculatedPosition.addInPlace(this.position);
}
var pose = this.rawPose;
if (poseData.orientation && pose.orientation) {
this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
if (this._mesh) {
if (this._mesh.getScene().useRightHandedSystem) {
this._deviceRoomRotationQuaternion.z *= -1;
this._deviceRoomRotationQuaternion.w *= -1;
} else {
this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
}
}
this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
}
}
};
PoseEnabledController2.prototype.attachToMesh = function(mesh2) {
if (this._mesh) {
this._mesh.parent = null;
}
this._mesh = mesh2;
if (this._poseControlledCamera) {
this._mesh.parent = this._poseControlledCamera;
}
if (!this._mesh.rotationQuaternion) {
this._mesh.rotationQuaternion = new BABYLON2.Quaternion();
}
this._updatePoseAndMesh();
if (this._pointingPoseNode) {
var parents = [];
var obj = this._pointingPoseNode;
while (obj.parent) {
parents.push(obj.parent);
obj = obj.parent;
}
parents.reverse().forEach(function(p) {
p.computeWorldMatrix(true);
});
}
this._meshAttachedObservable.notifyObservers(mesh2);
};
PoseEnabledController2.prototype.attachToPoseControlledCamera = function(camera2) {
this._poseControlledCamera = camera2;
if (this._mesh) {
this._mesh.parent = this._poseControlledCamera;
}
};
PoseEnabledController2.prototype.dispose = function() {
if (this._mesh) {
this._mesh.dispose();
}
this._mesh = null;
_super.prototype.dispose.call(this);
};
Object.defineProperty(PoseEnabledController2.prototype, "mesh", {
/**
* The mesh that is attached to the controller
*/
get: function() {
return this._mesh;
},
enumerable: true,
configurable: true
});
PoseEnabledController2.prototype.getForwardRay = function(length) {
if (length === void 0) {
length = 100;
}
if (!this.mesh) {
return new BABYLON2.Ray(BABYLON2.Vector3.Zero(), new BABYLON2.Vector3(0, 0, 1), length);
}
var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
var origin = m.getTranslation();
var forward = new BABYLON2.Vector3(0, 0, -1);
var forwardWorld = BABYLON2.Vector3.TransformNormal(forward, m);
var direction = BABYLON2.Vector3.Normalize(forwardWorld);
return new BABYLON2.Ray(origin, direction, length);
};
PoseEnabledController2.POINTING_POSE = "POINTING_POSE";
return PoseEnabledController2;
}(BABYLON2.Gamepad)
);
BABYLON2.PoseEnabledController = PoseEnabledController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var WebVRController = (
/** @class */
function(_super) {
__extends(WebVRController2, _super);
function WebVRController2(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this.onTriggerStateChangedObservable = new BABYLON2.Observable();
_this.onMainButtonStateChangedObservable = new BABYLON2.Observable();
_this.onSecondaryButtonStateChangedObservable = new BABYLON2.Observable();
_this.onPadStateChangedObservable = new BABYLON2.Observable();
_this.onPadValuesChangedObservable = new BABYLON2.Observable();
_this.pad = { x: 0, y: 0 };
_this._changes = {
pressChanged: false,
touchChanged: false,
valueChanged: false,
changed: false
};
_this._buttons = new Array(vrGamepad.buttons.length);
_this.hand = vrGamepad.hand;
return _this;
}
WebVRController2.prototype.onButtonStateChange = function(callback) {
this._onButtonStateChange = callback;
};
Object.defineProperty(WebVRController2.prototype, "defaultModel", {
/**
* The default controller model for the controller
*/
get: function() {
return this._defaultModel;
},
enumerable: true,
configurable: true
});
WebVRController2.prototype.update = function() {
_super.prototype.update.call(this);
for (var index = 0; index < this._buttons.length; index++) {
this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
}
if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
this.pad.x = this.leftStick.x;
this.pad.y = this.leftStick.y;
this.onPadValuesChangedObservable.notifyObservers(this.pad);
}
};
WebVRController2.prototype._setButtonValue = function(newState, currentState, buttonIndex) {
if (!newState) {
newState = {
pressed: false,
touched: false,
value: 0
};
}
if (!currentState) {
this._buttons[buttonIndex] = {
pressed: newState.pressed,
touched: newState.touched,
value: newState.value
};
return;
}
this._checkChanges(newState, currentState);
if (this._changes.changed) {
this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
this._handleButtonChange(buttonIndex, newState, this._changes);
}
this._buttons[buttonIndex].pressed = newState.pressed;
this._buttons[buttonIndex].touched = newState.touched;
this._buttons[buttonIndex].value = newState.value < 1e-8 ? 0 : newState.value;
};
WebVRController2.prototype._checkChanges = function(newState, currentState) {
this._changes.pressChanged = newState.pressed !== currentState.pressed;
this._changes.touchChanged = newState.touched !== currentState.touched;
this._changes.valueChanged = newState.value !== currentState.value;
this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
return this._changes;
};
WebVRController2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
this.onTriggerStateChangedObservable.clear();
this.onMainButtonStateChangedObservable.clear();
this.onSecondaryButtonStateChangedObservable.clear();
this.onPadStateChangedObservable.clear();
this.onPadValuesChangedObservable.clear();
};
return WebVRController2;
}(BABYLON2.PoseEnabledController)
);
BABYLON2.WebVRController = WebVRController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var OculusTouchController = (
/** @class */
function(_super) {
__extends(OculusTouchController2, _super);
function OculusTouchController2(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this.onSecondaryTriggerStateChangedObservable = new BABYLON2.Observable();
_this.onThumbRestChangedObservable = new BABYLON2.Observable();
_this.controllerType = BABYLON2.PoseEnabledControllerType.OCULUS;
return _this;
}
OculusTouchController2.prototype.initControllerMesh = function(scene, meshLoaded) {
var _this = this;
var meshName;
if (this.hand === "left") {
meshName = OculusTouchController2.MODEL_LEFT_FILENAME;
} else {
meshName = OculusTouchController2.MODEL_RIGHT_FILENAME;
}
BABYLON2.SceneLoader.ImportMesh("", OculusTouchController2.MODEL_BASE_URL, meshName, scene, function(newMeshes) {
_this._defaultModel = newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
Object.defineProperty(OculusTouchController2.prototype, "onAButtonStateChangedObservable", {
/**
* Fired when the A button on this controller is modified
*/
get: function() {
if (this.hand === "right") {
return this.onMainButtonStateChangedObservable;
} else {
throw new Error("No A button on left hand");
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(OculusTouchController2.prototype, "onBButtonStateChangedObservable", {
/**
* Fired when the B button on this controller is modified
*/
get: function() {
if (this.hand === "right") {
return this.onSecondaryButtonStateChangedObservable;
} else {
throw new Error("No B button on left hand");
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(OculusTouchController2.prototype, "onXButtonStateChangedObservable", {
/**
* Fired when the X button on this controller is modified
*/
get: function() {
if (this.hand === "left") {
return this.onMainButtonStateChangedObservable;
} else {
throw new Error("No X button on right hand");
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(OculusTouchController2.prototype, "onYButtonStateChangedObservable", {
/**
* Fired when the Y button on this controller is modified
*/
get: function() {
if (this.hand === "left") {
return this.onSecondaryButtonStateChangedObservable;
} else {
throw new Error("No Y button on right hand");
}
},
enumerable: true,
configurable: true
});
OculusTouchController2.prototype._handleButtonChange = function(buttonIdx, state, changes) {
var notifyObject = state;
var triggerDirection = this.hand === "right" ? -1 : 1;
switch (buttonIdx) {
case 0:
this.onPadStateChangedObservable.notifyObservers(notifyObject);
return;
case 1:
if (this._defaultModel) {
this._defaultModel.getChildren()[3].rotation.x = -notifyObject.value * 0.2;
this._defaultModel.getChildren()[3].position.y = -notifyObject.value * 5e-3;
this._defaultModel.getChildren()[3].position.z = -notifyObject.value * 5e-3;
}
this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
return;
case 2:
if (this._defaultModel) {
this._defaultModel.getChildren()[4].position.x = triggerDirection * notifyObject.value * 35e-4;
}
this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
return;
case 3:
if (this._defaultModel) {
if (notifyObject.pressed) {
this._defaultModel.getChildren()[1].position.y = -1e-3;
} else {
this._defaultModel.getChildren()[1].position.y = 0;
}
}
this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
return;
case 4:
if (this._defaultModel) {
if (notifyObject.pressed) {
this._defaultModel.getChildren()[2].position.y = -1e-3;
} else {
this._defaultModel.getChildren()[2].position.y = 0;
}
}
this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
return;
case 5:
this.onThumbRestChangedObservable.notifyObservers(notifyObject);
return;
}
};
OculusTouchController2.MODEL_BASE_URL = "https://controllers.babylonjs.com/oculus/";
OculusTouchController2.MODEL_LEFT_FILENAME = "left.babylon";
OculusTouchController2.MODEL_RIGHT_FILENAME = "right.babylon";
return OculusTouchController2;
}(BABYLON2.WebVRController)
);
BABYLON2.OculusTouchController = OculusTouchController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ViveController = (
/** @class */
function(_super) {
__extends(ViveController2, _super);
function ViveController2(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this.controllerType = BABYLON2.PoseEnabledControllerType.VIVE;
_this._invertLeftStickY = true;
return _this;
}
ViveController2.prototype.initControllerMesh = function(scene, meshLoaded) {
var _this = this;
BABYLON2.SceneLoader.ImportMesh("", ViveController2.MODEL_BASE_URL, ViveController2.MODEL_FILENAME, scene, function(newMeshes) {
_this._defaultModel = newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
Object.defineProperty(ViveController2.prototype, "onLeftButtonStateChangedObservable", {
/**
* Fired when the left button on this controller is modified
*/
get: function() {
return this.onMainButtonStateChangedObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViveController2.prototype, "onRightButtonStateChangedObservable", {
/**
* Fired when the right button on this controller is modified
*/
get: function() {
return this.onMainButtonStateChangedObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ViveController2.prototype, "onMenuButtonStateChangedObservable", {
/**
* Fired when the menu button on this controller is modified
*/
get: function() {
return this.onSecondaryButtonStateChangedObservable;
},
enumerable: true,
configurable: true
});
ViveController2.prototype._handleButtonChange = function(buttonIdx, state, changes) {
var notifyObject = state;
switch (buttonIdx) {
case 0:
this.onPadStateChangedObservable.notifyObservers(notifyObject);
return;
case 1:
if (this._defaultModel) {
this._defaultModel.getChildren()[6].rotation.x = -notifyObject.value * 0.15;
}
this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
return;
case 2:
this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
return;
case 3:
if (this._defaultModel) {
if (notifyObject.pressed) {
this._defaultModel.getChildren()[2].position.y = -1e-3;
} else {
this._defaultModel.getChildren()[2].position.y = 0;
}
}
this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
return;
}
};
ViveController2.MODEL_BASE_URL = "https://controllers.babylonjs.com/vive/";
ViveController2.MODEL_FILENAME = "wand.babylon";
return ViveController2;
}(BABYLON2.WebVRController)
);
BABYLON2.ViveController = ViveController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var GenericController = (
/** @class */
function(_super) {
__extends(GenericController2, _super);
function GenericController2(vrGamepad) {
return _super.call(this, vrGamepad) || this;
}
GenericController2.prototype.initControllerMesh = function(scene, meshLoaded) {
var _this = this;
BABYLON2.SceneLoader.ImportMesh("", GenericController2.MODEL_BASE_URL, GenericController2.MODEL_FILENAME, scene, function(newMeshes) {
_this._defaultModel = newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
GenericController2.prototype._handleButtonChange = function(buttonIdx, state, changes) {
console.log("Button id: " + buttonIdx + "state: ");
console.dir(state);
};
GenericController2.MODEL_BASE_URL = "https://controllers.babylonjs.com/generic/";
GenericController2.MODEL_FILENAME = "generic.babylon";
return GenericController2;
}(BABYLON2.WebVRController)
);
BABYLON2.GenericController = GenericController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var LoadedMeshInfo = (
/** @class */
function() {
function LoadedMeshInfo2() {
this.buttonMeshes = {};
this.axisMeshes = {};
}
return LoadedMeshInfo2;
}()
);
var WindowsMotionController = (
/** @class */
function(_super) {
__extends(WindowsMotionController2, _super);
function WindowsMotionController2(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this._mapping = {
// Semantic button names
buttons: ["thumbstick", "trigger", "grip", "menu", "trackpad"],
// A mapping of the button name to glTF model node name
// that should be transformed by button value.
buttonMeshNames: {
"trigger": "SELECT",
"menu": "MENU",
"grip": "GRASP",
"thumbstick": "THUMBSTICK_PRESS",
"trackpad": "TOUCHPAD_PRESS"
},
// This mapping is used to translate from the Motion Controller to Babylon semantics
buttonObservableNames: {
"trigger": "onTriggerStateChangedObservable",
"menu": "onSecondaryButtonStateChangedObservable",
"grip": "onMainButtonStateChangedObservable",
"thumbstick": "onPadStateChangedObservable",
"trackpad": "onTrackpadChangedObservable"
},
// A mapping of the axis name to glTF model node name
// that should be transformed by axis value.
// This array mirrors the browserGamepad.axes array, such that
// the mesh corresponding to axis 0 is in this array index 0.
axisMeshNames: [
"THUMBSTICK_X",
"THUMBSTICK_Y",
"TOUCHPAD_TOUCH_X",
"TOUCHPAD_TOUCH_Y"
],
pointingPoseMeshName: BABYLON2.PoseEnabledController.POINTING_POSE
};
_this.onTrackpadChangedObservable = new BABYLON2.Observable();
_this.onTrackpadValuesChangedObservable = new BABYLON2.Observable();
_this.trackpad = { x: 0, y: 0 };
_this.controllerType = BABYLON2.PoseEnabledControllerType.WINDOWS;
_this._loadedMeshInfo = null;
return _this;
}
Object.defineProperty(WindowsMotionController2.prototype, "onTriggerButtonStateChangedObservable", {
/**
* Fired when the trigger on this controller is modified
*/
get: function() {
return this.onTriggerStateChangedObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WindowsMotionController2.prototype, "onMenuButtonStateChangedObservable", {
/**
* Fired when the menu button on this controller is modified
*/
get: function() {
return this.onSecondaryButtonStateChangedObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WindowsMotionController2.prototype, "onGripButtonStateChangedObservable", {
/**
* Fired when the grip button on this controller is modified
*/
get: function() {
return this.onMainButtonStateChangedObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WindowsMotionController2.prototype, "onThumbstickButtonStateChangedObservable", {
/**
* Fired when the thumbstick button on this controller is modified
*/
get: function() {
return this.onPadStateChangedObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WindowsMotionController2.prototype, "onTouchpadButtonStateChangedObservable", {
/**
* Fired when the touchpad button on this controller is modified
*/
get: function() {
return this.onTrackpadChangedObservable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WindowsMotionController2.prototype, "onTouchpadValuesChangedObservable", {
/**
* Fired when the touchpad values on this controller are modified
*/
get: function() {
return this.onTrackpadValuesChangedObservable;
},
enumerable: true,
configurable: true
});
WindowsMotionController2.prototype._updateTrackpad = function() {
if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
this.trackpad.x = this.browserGamepad["axes"][2];
this.trackpad.y = this.browserGamepad["axes"][3];
this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
}
};
WindowsMotionController2.prototype.update = function() {
_super.prototype.update.call(this);
if (this.browserGamepad.axes) {
this._updateTrackpad();
if (this._loadedMeshInfo) {
for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
}
}
}
};
WindowsMotionController2.prototype._handleButtonChange = function(buttonIdx, state, changes) {
var buttonName = this._mapping.buttons[buttonIdx];
if (!buttonName) {
return;
}
this._updateTrackpad();
var observable = this[this._mapping.buttonObservableNames[buttonName]];
if (observable) {
observable.notifyObservers(state);
}
this._lerpButtonTransform(buttonName, state.value);
};
WindowsMotionController2.prototype._lerpButtonTransform = function(buttonName, buttonValue) {
if (!this._loadedMeshInfo) {
return;
}
var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
return;
}
BABYLON2.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
BABYLON2.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
};
WindowsMotionController2.prototype._lerpAxisTransform = function(axis, axisValue) {
if (!this._loadedMeshInfo) {
return;
}
var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
if (!meshInfo) {
return;
}
if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
return;
}
var lerpValue = axisValue * 0.5 + 0.5;
BABYLON2.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
BABYLON2.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
};
WindowsMotionController2.prototype.initControllerMesh = function(scene, meshLoaded, forceDefault) {
var _this = this;
if (forceDefault === void 0) {
forceDefault = false;
}
var path;
var filename;
if (BABYLON2.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
var device = "default";
if (this.id && !forceDefault) {
var match = this.id.match(WindowsMotionController2.GAMEPAD_ID_PATTERN);
device = match && match[0] || device;
}
if (this.hand === "left") {
filename = WindowsMotionController2.MODEL_LEFT_FILENAME;
} else {
filename = WindowsMotionController2.MODEL_RIGHT_FILENAME;
}
path = WindowsMotionController2.MODEL_BASE_URL + device + "/";
} else {
BABYLON2.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
path = BABYLON2.GenericController.MODEL_BASE_URL;
filename = BABYLON2.GenericController.MODEL_FILENAME;
}
BABYLON2.SceneLoader.ImportMesh("", path, filename, scene, function(meshes) {
_this._loadedMeshInfo = _this.processModel(scene, meshes);
if (!_this._loadedMeshInfo) {
return;
}
_this._defaultModel = _this._loadedMeshInfo.rootNode;
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
}, null, function(scene2, message) {
BABYLON2.Tools.Log(message);
BABYLON2.Tools.Warn("Failed to retrieve controller model from the remote server: " + path + filename);
if (!forceDefault) {
_this.initControllerMesh(scene2, meshLoaded, true);
}
});
};
WindowsMotionController2.prototype.processModel = function(scene, meshes) {
var loadedMeshInfo = null;
var parentMesh = new BABYLON2.Mesh(this.id + " " + this.hand, scene);
var childMesh = null;
for (var i2 = 0; i2 < meshes.length; i2++) {
var mesh2 = meshes[i2];
if (!mesh2.parent) {
mesh2.isPickable = false;
childMesh = mesh2;
break;
}
}
if (childMesh) {
childMesh.setParent(parentMesh);
loadedMeshInfo = this.createMeshInfo(parentMesh);
} else {
BABYLON2.Tools.Warn("Could not find root node in model file.");
}
return loadedMeshInfo;
};
WindowsMotionController2.prototype.createMeshInfo = function(rootNode) {
var loadedMeshInfo = new LoadedMeshInfo();
var i2;
loadedMeshInfo.rootNode = rootNode;
loadedMeshInfo.buttonMeshes = {};
loadedMeshInfo.axisMeshes = {};
for (i2 = 0; i2 < this._mapping.buttons.length; i2++) {
var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i2]];
if (!buttonMeshName) {
BABYLON2.Tools.Log("Skipping unknown button at index: " + i2 + " with mapped name: " + this._mapping.buttons[i2]);
continue;
}
var buttonMesh = getChildByName(rootNode, buttonMeshName);
if (!buttonMesh) {
BABYLON2.Tools.Warn("Missing button mesh with name: " + buttonMeshName);
continue;
}
var buttonMeshInfo = {
index: i2,
value: getImmediateChildByName(buttonMesh, "VALUE"),
pressed: getImmediateChildByName(buttonMesh, "PRESSED"),
unpressed: getImmediateChildByName(buttonMesh, "UNPRESSED")
};
if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
loadedMeshInfo.buttonMeshes[this._mapping.buttons[i2]] = buttonMeshInfo;
} else {
BABYLON2.Tools.Warn("Missing button submesh under mesh with name: " + buttonMeshName + "(VALUE: " + !!buttonMeshInfo.value + ", PRESSED: " + !!buttonMeshInfo.pressed + ", UNPRESSED:" + !!buttonMeshInfo.unpressed + ")");
}
}
for (i2 = 0; i2 < this._mapping.axisMeshNames.length; i2++) {
var axisMeshName = this._mapping.axisMeshNames[i2];
if (!axisMeshName) {
BABYLON2.Tools.Log("Skipping unknown axis at index: " + i2);
continue;
}
var axisMesh = getChildByName(rootNode, axisMeshName);
if (!axisMesh) {
BABYLON2.Tools.Warn("Missing axis mesh with name: " + axisMeshName);
continue;
}
var axisMeshInfo = {
index: i2,
value: getImmediateChildByName(axisMesh, "VALUE"),
min: getImmediateChildByName(axisMesh, "MIN"),
max: getImmediateChildByName(axisMesh, "MAX")
};
if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
loadedMeshInfo.axisMeshes[i2] = axisMeshInfo;
} else {
BABYLON2.Tools.Warn("Missing axis submesh under mesh with name: " + axisMeshName + "(VALUE: " + !!axisMeshInfo.value + ", MIN: " + !!axisMeshInfo.min + ", MAX:" + !!axisMeshInfo.max + ")");
}
}
loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
if (!loadedMeshInfo.pointingPoseNode) {
BABYLON2.Tools.Warn("Missing pointing pose mesh with name: " + this._mapping.pointingPoseMeshName);
} else {
this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
}
return loadedMeshInfo;
function getChildByName(node, name) {
return node.getChildMeshes(false, function(n) {
return n.name === name;
})[0];
}
function getImmediateChildByName(node, name) {
return node.getChildMeshes(true, function(n) {
return n.name == name;
})[0];
}
};
WindowsMotionController2.prototype.getForwardRay = function(length) {
if (length === void 0) {
length = 100;
}
if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
return _super.prototype.getForwardRay.call(this, length);
}
var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
var origin = m.getTranslation();
var forward = new BABYLON2.Vector3(0, 0, -1);
var forwardWorld = BABYLON2.Vector3.TransformNormal(forward, m);
var direction = BABYLON2.Vector3.Normalize(forwardWorld);
return new BABYLON2.Ray(origin, direction, length);
};
WindowsMotionController2.prototype.dispose = function() {
_super.prototype.dispose.call(this);
this.onTrackpadChangedObservable.clear();
};
WindowsMotionController2.MODEL_BASE_URL = "https://controllers.babylonjs.com/microsoft/";
WindowsMotionController2.MODEL_LEFT_FILENAME = "left.glb";
WindowsMotionController2.MODEL_RIGHT_FILENAME = "right.glb";
WindowsMotionController2.GAMEPAD_ID_PREFIX = "Spatial Controller (Spatial Interaction Source) ";
WindowsMotionController2.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
return WindowsMotionController2;
}(BABYLON2.WebVRController)
);
BABYLON2.WindowsMotionController = WindowsMotionController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var GearVRController = (
/** @class */
function(_super) {
__extends(GearVRController2, _super);
function GearVRController2(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this._buttonIndexToObservableNameMap = [
"onTrackpadChangedObservable",
"onTriggerStateChangedObservable"
// Trigger
];
_this.controllerType = BABYLON2.PoseEnabledControllerType.GEAR_VR;
_this._calculatedPosition = new BABYLON2.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
_this._disableTrackPosition(_this._calculatedPosition);
return _this;
}
GearVRController2.prototype.initControllerMesh = function(scene, meshLoaded) {
var _this = this;
BABYLON2.SceneLoader.ImportMesh("", GearVRController2.MODEL_BASE_URL, GearVRController2.MODEL_FILENAME, scene, function(newMeshes) {
var mesh2 = new BABYLON2.Mesh("", scene);
newMeshes[1].parent = mesh2;
newMeshes[1].position.z = -0.15;
_this._defaultModel = mesh2;
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
GearVRController2.prototype._handleButtonChange = function(buttonIdx, state, changes) {
if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
var observable = this[observableName];
if (observable) {
observable.notifyObservers(state);
}
}
};
GearVRController2.MODEL_BASE_URL = "https://controllers.babylonjs.com/generic/";
GearVRController2.MODEL_FILENAME = "generic.babylon";
GearVRController2.GAMEPAD_ID_PREFIX = "Gear VR";
return GearVRController2;
}(BABYLON2.WebVRController)
);
BABYLON2.GearVRController = GearVRController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DaydreamController = (
/** @class */
function(_super) {
__extends(DaydreamController2, _super);
function DaydreamController2(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this.controllerType = BABYLON2.PoseEnabledControllerType.DAYDREAM;
return _this;
}
DaydreamController2.prototype.initControllerMesh = function(scene, meshLoaded) {
var _this = this;
BABYLON2.SceneLoader.ImportMesh("", DaydreamController2.MODEL_BASE_URL, DaydreamController2.MODEL_FILENAME, scene, function(newMeshes) {
_this._defaultModel = newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
DaydreamController2.prototype._handleButtonChange = function(buttonIdx, state, changes) {
if (buttonIdx === 0) {
var observable = this.onTriggerStateChangedObservable;
if (observable) {
observable.notifyObservers(state);
}
} else {
BABYLON2.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
}
};
DaydreamController2.MODEL_BASE_URL = "https://controllers.babylonjs.com/generic/";
DaydreamController2.MODEL_FILENAME = "generic.babylon";
DaydreamController2.GAMEPAD_ID_PREFIX = "Daydream";
return DaydreamController2;
}(BABYLON2.WebVRController)
);
BABYLON2.DaydreamController = DaydreamController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
Object.defineProperty(BABYLON2.Scene.prototype, "gamepadManager", {
get: function() {
if (!this._gamepadManager) {
this._gamepadManager = new BABYLON2.GamepadManager(this);
var component = this._getComponent(BABYLON2.SceneComponentConstants.NAME_GAMEPAD);
if (!component) {
component = new GamepadSystemSceneComponent(this);
this._addComponent(component);
}
}
return this._gamepadManager;
},
enumerable: true,
configurable: true
});
BABYLON2.FreeCameraInputsManager.prototype.addGamepad = function() {
this.add(new BABYLON2.FreeCameraGamepadInput());
return this;
};
BABYLON2.ArcRotateCameraInputsManager.prototype.addGamepad = function() {
this.add(new BABYLON2.ArcRotateCameraGamepadInput());
return this;
};
var GamepadSystemSceneComponent = (
/** @class */
function() {
function GamepadSystemSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_GAMEPAD;
this.scene = scene;
}
GamepadSystemSceneComponent2.prototype.register = function() {
this.scene._beforeCameraUpdateStage.registerStep(BABYLON2.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
};
GamepadSystemSceneComponent2.prototype.rebuild = function() {
};
GamepadSystemSceneComponent2.prototype.dispose = function() {
var gamepadManager = this.scene._gamepadManager;
if (gamepadManager) {
gamepadManager.dispose();
this.scene._gamepadManager = null;
}
};
GamepadSystemSceneComponent2.prototype._beforeCameraUpdate = function() {
var gamepadManager = this.scene._gamepadManager;
if (gamepadManager && gamepadManager._isMonitoring) {
gamepadManager._checkGamepadsStatus();
}
};
return GamepadSystemSceneComponent2;
}()
);
BABYLON2.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("FollowCamera", function(name, scene) {
return function() {
return new FollowCamera(name, BABYLON2.Vector3.Zero(), scene);
};
});
BABYLON2.Node.AddNodeConstructor("ArcFollowCamera", function(name, scene) {
return function() {
return new ArcFollowCamera(name, 0, 0, 1, null, scene);
};
});
var FollowCamera = (
/** @class */
function(_super) {
__extends(FollowCamera2, _super);
function FollowCamera2(name, position, scene, lockedTarget) {
if (lockedTarget === void 0) {
lockedTarget = null;
}
var _this = _super.call(this, name, position, scene) || this;
_this.radius = 12;
_this.rotationOffset = 0;
_this.heightOffset = 4;
_this.cameraAcceleration = 0.05;
_this.maxCameraSpeed = 20;
_this.lockedTarget = lockedTarget;
return _this;
}
FollowCamera2.prototype._follow = function(cameraTarget) {
if (!cameraTarget) {
return;
}
var yRotation;
if (cameraTarget.rotationQuaternion) {
var rotMatrix = new BABYLON2.Matrix();
cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
} else {
yRotation = cameraTarget.rotation.y;
}
var radians = BABYLON2.Tools.ToRadians(this.rotationOffset) + yRotation;
var targetPosition = cameraTarget.getAbsolutePosition();
var targetX = targetPosition.x + Math.sin(radians) * this.radius;
var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
var dx = targetX - this.position.x;
var dy = targetPosition.y + this.heightOffset - this.position.y;
var dz = targetZ - this.position.z;
var vx = dx * this.cameraAcceleration * 2;
var vy = dy * this.cameraAcceleration;
var vz = dz * this.cameraAcceleration * 2;
if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
}
if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
}
if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
}
this.position = new BABYLON2.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
this.setTarget(targetPosition);
};
FollowCamera2.prototype._checkInputs = function() {
_super.prototype._checkInputs.call(this);
if (this.lockedTarget) {
this._follow(this.lockedTarget);
}
};
FollowCamera2.prototype.getClassName = function() {
return "FollowCamera";
};
__decorate([
BABYLON2.serialize()
], FollowCamera2.prototype, "radius", void 0);
__decorate([
BABYLON2.serialize()
], FollowCamera2.prototype, "rotationOffset", void 0);
__decorate([
BABYLON2.serialize()
], FollowCamera2.prototype, "heightOffset", void 0);
__decorate([
BABYLON2.serialize()
], FollowCamera2.prototype, "cameraAcceleration", void 0);
__decorate([
BABYLON2.serialize()
], FollowCamera2.prototype, "maxCameraSpeed", void 0);
__decorate([
BABYLON2.serializeAsMeshReference("lockedTargetId")
], FollowCamera2.prototype, "lockedTarget", void 0);
return FollowCamera2;
}(BABYLON2.TargetCamera)
);
BABYLON2.FollowCamera = FollowCamera;
var ArcFollowCamera = (
/** @class */
function(_super) {
__extends(ArcFollowCamera2, _super);
function ArcFollowCamera2(name, alpha, beta, radius, target, scene) {
var _this = _super.call(this, name, BABYLON2.Vector3.Zero(), scene) || this;
_this.alpha = alpha;
_this.beta = beta;
_this.radius = radius;
_this.target = target;
_this._cartesianCoordinates = BABYLON2.Vector3.Zero();
_this._follow();
return _this;
}
ArcFollowCamera2.prototype._follow = function() {
if (!this.target) {
return;
}
this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
var targetPosition = this.target.getAbsolutePosition();
this.position = targetPosition.add(this._cartesianCoordinates);
this.setTarget(targetPosition);
};
ArcFollowCamera2.prototype._checkInputs = function() {
_super.prototype._checkInputs.call(this);
this._follow();
};
ArcFollowCamera2.prototype.getClassName = function() {
return "ArcFollowCamera";
};
return ArcFollowCamera2;
}(BABYLON2.TargetCamera)
);
BABYLON2.ArcFollowCamera = ArcFollowCamera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var UniversalCamera = (
/** @class */
function(_super) {
__extends(UniversalCamera2, _super);
function UniversalCamera2(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this.inputs.addGamepad();
return _this;
}
Object.defineProperty(UniversalCamera2.prototype, "gamepadAngularSensibility", {
/**
* Defines the gamepad rotation sensiblity.
* This is the threshold from when rotation starts to be accounted for to prevent jittering.
*/
get: function() {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
return gamepad.gamepadAngularSensibility;
}
return 0;
},
set: function(value) {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
gamepad.gamepadAngularSensibility = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(UniversalCamera2.prototype, "gamepadMoveSensibility", {
/**
* Defines the gamepad move sensiblity.
* This is the threshold from when moving starts to be accounted for for to prevent jittering.
*/
get: function() {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
return gamepad.gamepadMoveSensibility;
}
return 0;
},
set: function(value) {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
gamepad.gamepadMoveSensibility = value;
}
},
enumerable: true,
configurable: true
});
UniversalCamera2.prototype.getClassName = function() {
return "UniversalCamera";
};
return UniversalCamera2;
}(BABYLON2.TouchCamera)
);
BABYLON2.UniversalCamera = UniversalCamera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Node.AddNodeConstructor("GamepadCamera", function(name, scene) {
return function() {
return new GamepadCamera(name, BABYLON2.Vector3.Zero(), scene);
};
});
var GamepadCamera = (
/** @class */
function(_super) {
__extends(GamepadCamera2, _super);
function GamepadCamera2(name, position, scene) {
return _super.call(this, name, position, scene) || this;
}
GamepadCamera2.prototype.getClassName = function() {
return "GamepadCamera";
};
return GamepadCamera2;
}(BABYLON2.UniversalCamera)
);
BABYLON2.GamepadCamera = GamepadCamera;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PostProcessRenderPipelineManager = (
/** @class */
function() {
function PostProcessRenderPipelineManager2() {
this._renderPipelines = {};
}
PostProcessRenderPipelineManager2.prototype.addPipeline = function(renderPipeline) {
this._renderPipelines[renderPipeline._name] = renderPipeline;
};
PostProcessRenderPipelineManager2.prototype.attachCamerasToRenderPipeline = function(renderPipelineName, cameras, unique) {
if (unique === void 0) {
unique = false;
}
var renderPipeline = this._renderPipelines[renderPipelineName];
if (!renderPipeline) {
return;
}
renderPipeline._attachCameras(cameras, unique);
};
PostProcessRenderPipelineManager2.prototype.detachCamerasFromRenderPipeline = function(renderPipelineName, cameras) {
var renderPipeline = this._renderPipelines[renderPipelineName];
if (!renderPipeline) {
return;
}
renderPipeline._detachCameras(cameras);
};
PostProcessRenderPipelineManager2.prototype.enableEffectInPipeline = function(renderPipelineName, renderEffectName, cameras) {
var renderPipeline = this._renderPipelines[renderPipelineName];
if (!renderPipeline) {
return;
}
renderPipeline._enableEffect(renderEffectName, cameras);
};
PostProcessRenderPipelineManager2.prototype.disableEffectInPipeline = function(renderPipelineName, renderEffectName, cameras) {
var renderPipeline = this._renderPipelines[renderPipelineName];
if (!renderPipeline) {
return;
}
renderPipeline._disableEffect(renderEffectName, cameras);
};
PostProcessRenderPipelineManager2.prototype.update = function() {
for (var renderPipelineName in this._renderPipelines) {
if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
var pipeline = this._renderPipelines[renderPipelineName];
if (!pipeline.isSupported) {
pipeline.dispose();
delete this._renderPipelines[renderPipelineName];
} else {
pipeline._update();
}
}
}
};
PostProcessRenderPipelineManager2.prototype._rebuild = function() {
for (var renderPipelineName in this._renderPipelines) {
if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
var pipeline = this._renderPipelines[renderPipelineName];
pipeline._rebuild();
}
}
};
PostProcessRenderPipelineManager2.prototype.dispose = function() {
for (var renderPipelineName in this._renderPipelines) {
if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
var pipeline = this._renderPipelines[renderPipelineName];
pipeline.dispose();
}
}
};
return PostProcessRenderPipelineManager2;
}()
);
BABYLON2.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
Object.defineProperty(BABYLON2.Scene.prototype, "postProcessRenderPipelineManager", {
get: function() {
if (!this._postProcessRenderPipelineManager) {
var component = this._getComponent(BABYLON2.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
if (!component) {
component = new PostProcessRenderPipelineManagerSceneComponent(this);
this._addComponent(component);
}
this._postProcessRenderPipelineManager = new BABYLON2.PostProcessRenderPipelineManager();
}
return this._postProcessRenderPipelineManager;
},
enumerable: true,
configurable: true
});
var PostProcessRenderPipelineManagerSceneComponent = (
/** @class */
function() {
function PostProcessRenderPipelineManagerSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
this.scene = scene;
}
PostProcessRenderPipelineManagerSceneComponent2.prototype.register = function() {
this.scene._gatherRenderTargetsStage.registerStep(BABYLON2.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
};
PostProcessRenderPipelineManagerSceneComponent2.prototype.rebuild = function() {
if (this.scene._postProcessRenderPipelineManager) {
this.scene._postProcessRenderPipelineManager._rebuild();
}
};
PostProcessRenderPipelineManagerSceneComponent2.prototype.dispose = function() {
if (this.scene._postProcessRenderPipelineManager) {
this.scene._postProcessRenderPipelineManager.dispose();
}
};
PostProcessRenderPipelineManagerSceneComponent2.prototype._gatherRenderTargets = function(renderTargets) {
if (this.scene._postProcessRenderPipelineManager) {
this.scene._postProcessRenderPipelineManager.update();
}
};
return PostProcessRenderPipelineManagerSceneComponent2;
}()
);
BABYLON2.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PostProcessRenderEffect = (
/** @class */
function() {
function PostProcessRenderEffect2(engine, name, getPostProcesses, singleInstance) {
this._name = name;
this._singleInstance = singleInstance || true;
this._getPostProcesses = getPostProcesses;
this._cameras = {};
this._indicesForCamera = {};
this._postProcesses = {};
}
Object.defineProperty(PostProcessRenderEffect2.prototype, "isSupported", {
/**
* Checks if all the post processes in the effect are supported.
*/
get: function() {
for (var index in this._postProcesses) {
if (this._postProcesses.hasOwnProperty(index)) {
var pps = this._postProcesses[index];
for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
if (!pps[ppIndex].isSupported) {
return false;
}
}
}
}
return true;
},
enumerable: true,
configurable: true
});
PostProcessRenderEffect2.prototype._update = function() {
};
PostProcessRenderEffect2.prototype._attachCameras = function(cameras) {
var _this = this;
var cameraKey;
var cams = BABYLON2.Tools.MakeArray(cameras || this._cameras);
if (!cams) {
return;
}
for (var i2 = 0; i2 < cams.length; i2++) {
var camera2 = cams[i2];
var cameraName = camera2.name;
if (this._singleInstance) {
cameraKey = 0;
} else {
cameraKey = cameraName;
}
if (!this._postProcesses[cameraKey]) {
var postProcess = this._getPostProcesses();
if (postProcess) {
this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
}
}
if (!this._indicesForCamera[cameraName]) {
this._indicesForCamera[cameraName] = [];
}
this._postProcesses[cameraKey].forEach(function(postProcess2) {
var index = camera2.attachPostProcess(postProcess2);
_this._indicesForCamera[cameraName].push(index);
});
if (!this._cameras[cameraName]) {
this._cameras[cameraName] = camera2;
}
}
};
PostProcessRenderEffect2.prototype._detachCameras = function(cameras) {
var cams = BABYLON2.Tools.MakeArray(cameras || this._cameras);
if (!cams) {
return;
}
for (var i2 = 0; i2 < cams.length; i2++) {
var camera2 = cams[i2];
var cameraName = camera2.name;
this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function(postProcess) {
camera2.detachPostProcess(postProcess);
});
if (this._cameras[cameraName]) {
this._cameras[cameraName] = null;
}
}
};
PostProcessRenderEffect2.prototype._enable = function(cameras) {
var _this = this;
var cams = BABYLON2.Tools.MakeArray(cameras || this._cameras);
if (!cams) {
return;
}
for (var i2 = 0; i2 < cams.length; i2++) {
var camera2 = cams[i2];
var cameraName = camera2.name;
for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
if (camera2._postProcesses[this._indicesForCamera[cameraName][j]] === void 0 || camera2._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function(postProcess) {
cams[i2].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
});
}
}
}
};
PostProcessRenderEffect2.prototype._disable = function(cameras) {
var cams = BABYLON2.Tools.MakeArray(cameras || this._cameras);
if (!cams) {
return;
}
for (var i2 = 0; i2 < cams.length; i2++) {
var camera2 = cams[i2];
var cameraName = camera2.name;
this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function(postProcess) {
camera2.detachPostProcess(postProcess);
});
}
};
PostProcessRenderEffect2.prototype.getPostProcesses = function(camera2) {
if (this._singleInstance) {
return this._postProcesses[0];
} else {
if (!camera2) {
return null;
}
return this._postProcesses[camera2.name];
}
};
return PostProcessRenderEffect2;
}()
);
BABYLON2.PostProcessRenderEffect = PostProcessRenderEffect;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PostProcessRenderPipeline = (
/** @class */
function() {
function PostProcessRenderPipeline2(engine, name) {
this.engine = engine;
this._name = name;
this._renderEffects = {};
this._renderEffectsForIsolatedPass = new Array();
this._cameras = [];
}
PostProcessRenderPipeline2.prototype.getClassName = function() {
return "PostProcessRenderPipeline";
};
Object.defineProperty(PostProcessRenderPipeline2.prototype, "isSupported", {
/**
* If all the render effects in the pipeline are support
*/
get: function() {
for (var renderEffectName in this._renderEffects) {
if (this._renderEffects.hasOwnProperty(renderEffectName)) {
if (!this._renderEffects[renderEffectName].isSupported) {
return false;
}
}
}
return true;
},
enumerable: true,
configurable: true
});
PostProcessRenderPipeline2.prototype.addEffect = function(renderEffect) {
this._renderEffects[renderEffect._name] = renderEffect;
};
PostProcessRenderPipeline2.prototype._rebuild = function() {
};
PostProcessRenderPipeline2.prototype._enableEffect = function(renderEffectName, cameras) {
var renderEffects = this._renderEffects[renderEffectName];
if (!renderEffects) {
return;
}
renderEffects._enable(BABYLON2.Tools.MakeArray(cameras || this._cameras));
};
PostProcessRenderPipeline2.prototype._disableEffect = function(renderEffectName, cameras) {
var renderEffects = this._renderEffects[renderEffectName];
if (!renderEffects) {
return;
}
renderEffects._disable(BABYLON2.Tools.MakeArray(cameras || this._cameras));
};
PostProcessRenderPipeline2.prototype._attachCameras = function(cameras, unique) {
var cams = BABYLON2.Tools.MakeArray(cameras || this._cameras);
if (!cams) {
return;
}
var indicesToDelete = [];
var i2;
for (i2 = 0; i2 < cams.length; i2++) {
var camera2 = cams[i2];
var cameraName = camera2.name;
if (this._cameras.indexOf(camera2) === -1) {
this._cameras[cameraName] = camera2;
} else if (unique) {
indicesToDelete.push(i2);
}
}
for (i2 = 0; i2 < indicesToDelete.length; i2++) {
cameras.splice(indicesToDelete[i2], 1);
}
for (var renderEffectName in this._renderEffects) {
if (this._renderEffects.hasOwnProperty(renderEffectName)) {
this._renderEffects[renderEffectName]._attachCameras(cams);
}
}
};
PostProcessRenderPipeline2.prototype._detachCameras = function(cameras) {
var cams = BABYLON2.Tools.MakeArray(cameras || this._cameras);
if (!cams) {
return;
}
for (var renderEffectName in this._renderEffects) {
if (this._renderEffects.hasOwnProperty(renderEffectName)) {
this._renderEffects[renderEffectName]._detachCameras(cams);
}
}
for (var i2 = 0; i2 < cams.length; i2++) {
this._cameras.splice(this._cameras.indexOf(cams[i2]), 1);
}
};
PostProcessRenderPipeline2.prototype._update = function() {
for (var renderEffectName in this._renderEffects) {
if (this._renderEffects.hasOwnProperty(renderEffectName)) {
this._renderEffects[renderEffectName]._update();
}
}
for (var i2 = 0; i2 < this._cameras.length; i2++) {
var cameraName = this._cameras[i2].name;
if (this._renderEffectsForIsolatedPass[cameraName]) {
this._renderEffectsForIsolatedPass[cameraName]._update();
}
}
};
PostProcessRenderPipeline2.prototype._reset = function() {
this._renderEffects = {};
this._renderEffectsForIsolatedPass = new Array();
};
PostProcessRenderPipeline2.prototype._enableMSAAOnFirstPostProcess = function(sampleCount) {
var effectKeys = Object.keys(this._renderEffects);
if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
if (postProcesses) {
postProcesses[0].samples = sampleCount;
return true;
}
}
return false;
};
PostProcessRenderPipeline2.prototype.dispose = function() {
};
__decorate([
BABYLON2.serialize()
], PostProcessRenderPipeline2.prototype, "_name", void 0);
return PostProcessRenderPipeline2;
}()
);
BABYLON2.PostProcessRenderPipeline = PostProcessRenderPipeline;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DepthRenderer = (
/** @class */
function() {
function DepthRenderer2(scene, type, camera2) {
if (type === void 0) {
type = BABYLON2.Engine.TEXTURETYPE_FLOAT;
}
if (camera2 === void 0) {
camera2 = null;
}
var _this = this;
this.useOnlyInActiveCamera = false;
this._scene = scene;
var component = scene._getComponent(BABYLON2.SceneComponentConstants.NAME_DEPTHRENDERER);
if (!component) {
component = new BABYLON2.DepthRendererSceneComponent(scene);
scene._addComponent(component);
}
this._camera = camera2;
var engine = scene.getEngine();
this._depthMap = new BABYLON2.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
this._depthMap.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._depthMap.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._depthMap.refreshRate = 1;
this._depthMap.renderParticles = false;
this._depthMap.renderList = null;
this._depthMap.activeCamera = this._camera;
this._depthMap.ignoreCameraViewport = true;
this._depthMap.useCameraPostProcesses = false;
this._depthMap.onClearObservable.add(function(engine2) {
engine2.clear(new BABYLON2.Color4(1, 1, 1, 1), true, true, true);
});
var renderSubMesh = function(subMesh) {
var mesh2 = subMesh.getRenderingMesh();
var scene2 = _this._scene;
var engine2 = scene2.getEngine();
var material = subMesh.getMaterial();
if (!material) {
return;
}
engine2.setState(material.backFaceCulling, 0, false, scene2.useRightHandedSystem);
var batch = mesh2._getInstancesRenderList(subMesh._id);
if (batch.mustReturn) {
return;
}
var hardwareInstancedRendering = engine2.getCaps().instancedArrays && batch.visibleInstances[subMesh._id] !== null;
var camera3 = _this._camera || scene2.activeCamera;
if (_this.isReady(subMesh, hardwareInstancedRendering) && camera3) {
engine2.enableEffect(_this._effect);
mesh2._bind(subMesh, _this._effect, BABYLON2.Material.TriangleFillMode);
_this._effect.setMatrix("viewProjection", scene2.getTransformMatrix());
_this._effect.setFloat2("depthValues", camera3.minZ, camera3.minZ + camera3.maxZ);
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
_this._effect.setTexture("diffuseSampler", alphaTexture);
_this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
_this._effect.setMatrices("mBones", mesh2.skeleton.getTransformMatrices(mesh2));
}
mesh2._processRendering(subMesh, _this._effect, BABYLON2.Material.TriangleFillMode, batch, hardwareInstancedRendering, function(isInstance, world) {
return _this._effect.setMatrix("world", world);
});
}
};
this._depthMap.customRenderFunction = function(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
var index;
if (depthOnlySubMeshes.length) {
engine.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
renderSubMesh(depthOnlySubMeshes.data[index]);
}
engine.setColorWrite(true);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
renderSubMesh(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
renderSubMesh(alphaTestSubMeshes.data[index]);
}
};
}
DepthRenderer2.prototype.isReady = function(subMesh, useInstances) {
var material = subMesh.getMaterial();
if (material.disableDepthWrite) {
return false;
}
var defines = [];
var attribs = [BABYLON2.VertexBuffer.PositionKind];
var mesh2 = subMesh.getMesh();
if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
defines.push("#define ALPHATEST");
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
defines.push("#define UV1");
}
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind)) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
defines.push("#define UV2");
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (mesh2.numBoneInfluencers > 4) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
defines.push("#define BonesPerMesh " + (mesh2.skeleton ? mesh2.skeleton.bones.length + 1 : 0));
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
if (useInstances) {
defines.push("#define INSTANCES");
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
}
return this._effect.isReady();
};
DepthRenderer2.prototype.getDepthMap = function() {
return this._depthMap;
};
DepthRenderer2.prototype.dispose = function() {
this._depthMap.dispose();
};
return DepthRenderer2;
}()
);
BABYLON2.DepthRenderer = DepthRenderer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Scene.prototype.enableDepthRenderer = function(camera2) {
camera2 = camera2 || this.activeCamera;
if (!camera2) {
throw "No camera available to enable depth renderer";
}
if (!this._depthRenderer) {
this._depthRenderer = {};
}
if (!this._depthRenderer[camera2.id]) {
var textureType = 0;
if (this.getEngine().getCaps().textureHalfFloatRender) {
textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
} else if (this.getEngine().getCaps().textureFloatRender) {
textureType = BABYLON2.Engine.TEXTURETYPE_FLOAT;
} else {
throw "Depth renderer does not support int texture type";
}
this._depthRenderer[camera2.id] = new BABYLON2.DepthRenderer(this, textureType, camera2);
}
return this._depthRenderer[camera2.id];
};
BABYLON2.Scene.prototype.disableDepthRenderer = function(camera2) {
camera2 = camera2 || this.activeCamera;
if (!camera2 || !this._depthRenderer || !this._depthRenderer[camera2.id]) {
return;
}
this._depthRenderer[camera2.id].dispose();
delete this._depthRenderer[camera2.id];
};
var DepthRendererSceneComponent = (
/** @class */
function() {
function DepthRendererSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_DEPTHRENDERER;
this.scene = scene;
}
DepthRendererSceneComponent2.prototype.register = function() {
this.scene._gatherRenderTargetsStage.registerStep(BABYLON2.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON2.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
};
DepthRendererSceneComponent2.prototype.rebuild = function() {
};
DepthRendererSceneComponent2.prototype.dispose = function() {
for (var key in this.scene._depthRenderer) {
this.scene._depthRenderer[key].dispose();
}
};
DepthRendererSceneComponent2.prototype._gatherRenderTargets = function(renderTargets) {
if (this.scene._depthRenderer) {
for (var key in this.scene._depthRenderer) {
var depthRenderer = this.scene._depthRenderer[key];
if (!depthRenderer.useOnlyInActiveCamera) {
renderTargets.push(depthRenderer.getDepthMap());
}
}
}
};
DepthRendererSceneComponent2.prototype._gatherActiveCameraRenderTargets = function(renderTargets) {
if (this.scene._depthRenderer) {
for (var key in this.scene._depthRenderer) {
var depthRenderer = this.scene._depthRenderer[key];
if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
renderTargets.push(depthRenderer.getDepthMap());
}
}
}
};
return DepthRendererSceneComponent2;
}()
);
BABYLON2.DepthRendererSceneComponent = DepthRendererSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var GeometryBufferRenderer = (
/** @class */
function() {
function GeometryBufferRenderer2(scene, ratio) {
if (ratio === void 0) {
ratio = 1;
}
this._enablePosition = false;
this._scene = scene;
this._ratio = ratio;
var component = scene._getComponent(BABYLON2.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
if (!component) {
component = new BABYLON2.GeometryBufferRendererSceneComponent(scene);
scene._addComponent(component);
}
this._createRenderTargets();
}
Object.defineProperty(GeometryBufferRenderer2.prototype, "renderList", {
/**
* Set the render list (meshes to be rendered) used in the G buffer.
*/
set: function(meshes) {
this._multiRenderTarget.renderList = meshes;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GeometryBufferRenderer2.prototype, "isSupported", {
/**
* Gets wether or not G buffer are supported by the running hardware.
* This requires draw buffer supports
*/
get: function() {
return this._multiRenderTarget.isSupported;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GeometryBufferRenderer2.prototype, "enablePosition", {
/**
* Gets wether or not position are enabled for the G buffer.
*/
get: function() {
return this._enablePosition;
},
/**
* Sets wether or not position are enabled for the G buffer.
*/
set: function(enable) {
this._enablePosition = enable;
this.dispose();
this._createRenderTargets();
},
enumerable: true,
configurable: true
});
Object.defineProperty(GeometryBufferRenderer2.prototype, "scene", {
/**
* Gets the scene associated with the buffer.
*/
get: function() {
return this._scene;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GeometryBufferRenderer2.prototype, "ratio", {
/**
* Gets the ratio used by the buffer during its creation.
* How big is the buffer related to the main canvas.
*/
get: function() {
return this._ratio;
},
enumerable: true,
configurable: true
});
GeometryBufferRenderer2.prototype.isReady = function(subMesh, useInstances) {
var material = subMesh.getMaterial();
if (material && material.disableDepthWrite) {
return false;
}
var defines = [];
var attribs = [BABYLON2.VertexBuffer.PositionKind, BABYLON2.VertexBuffer.NormalKind];
var mesh2 = subMesh.getMesh();
if (material && material.needAlphaTesting()) {
defines.push("#define ALPHATEST");
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
defines.push("#define UV1");
}
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind)) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
defines.push("#define UV2");
}
}
if (this._enablePosition) {
defines.push("#define POSITION");
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (mesh2.numBoneInfluencers > 4) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
defines.push("#define BonesPerMesh " + (mesh2.skeleton ? mesh2.skeleton.bones.length + 1 : 0));
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
if (useInstances) {
defines.push("#define INSTANCES");
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, void 0, void 0, void 0, { buffersCount: this._enablePosition ? 3 : 2 });
}
return this._effect.isReady();
};
GeometryBufferRenderer2.prototype.getGBuffer = function() {
return this._multiRenderTarget;
};
Object.defineProperty(GeometryBufferRenderer2.prototype, "samples", {
/**
* Gets the number of samples used to render the buffer (anti aliasing).
*/
get: function() {
return this._multiRenderTarget.samples;
},
/**
* Sets the number of samples used to render the buffer (anti aliasing).
*/
set: function(value) {
this._multiRenderTarget.samples = value;
},
enumerable: true,
configurable: true
});
GeometryBufferRenderer2.prototype.dispose = function() {
this.getGBuffer().dispose();
};
GeometryBufferRenderer2.prototype._createRenderTargets = function() {
var _this = this;
var engine = this._scene.getEngine();
var count = this._enablePosition ? 3 : 2;
this._multiRenderTarget = new BABYLON2.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON2.Engine.TEXTURETYPE_FLOAT });
if (!this.isSupported) {
return;
}
this._multiRenderTarget.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._multiRenderTarget.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._multiRenderTarget.refreshRate = 1;
this._multiRenderTarget.renderParticles = false;
this._multiRenderTarget.renderList = null;
this._multiRenderTarget.onClearObservable.add(function(engine2) {
engine2.clear(new BABYLON2.Color4(0, 0, 0, 1), true, true, true);
});
var renderSubMesh = function(subMesh) {
var mesh2 = subMesh.getRenderingMesh();
var scene = _this._scene;
var engine2 = scene.getEngine();
var material = subMesh.getMaterial();
if (!material) {
return;
}
engine2.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
var batch = mesh2._getInstancesRenderList(subMesh._id);
if (batch.mustReturn) {
return;
}
var hardwareInstancedRendering = engine2.getCaps().instancedArrays && batch.visibleInstances[subMesh._id] !== null;
if (_this.isReady(subMesh, hardwareInstancedRendering)) {
engine2.enableEffect(_this._effect);
mesh2._bind(subMesh, _this._effect, BABYLON2.Material.TriangleFillMode);
_this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
_this._effect.setMatrix("view", scene.getViewMatrix());
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
_this._effect.setTexture("diffuseSampler", alphaTexture);
_this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
_this._effect.setMatrices("mBones", mesh2.skeleton.getTransformMatrices(mesh2));
}
mesh2._processRendering(subMesh, _this._effect, BABYLON2.Material.TriangleFillMode, batch, hardwareInstancedRendering, function(isInstance, world) {
return _this._effect.setMatrix("world", world);
});
}
};
this._multiRenderTarget.customRenderFunction = function(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
var index;
if (depthOnlySubMeshes.length) {
engine.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
renderSubMesh(depthOnlySubMeshes.data[index]);
}
engine.setColorWrite(true);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
renderSubMesh(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
renderSubMesh(alphaTestSubMeshes.data[index]);
}
};
};
return GeometryBufferRenderer2;
}()
);
BABYLON2.GeometryBufferRenderer = GeometryBufferRenderer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
Object.defineProperty(BABYLON2.Scene.prototype, "geometryBufferRenderer", {
get: function() {
this._geometryBufferRenderer;
},
set: function(value) {
if (value && value.isSupported) {
this._geometryBufferRenderer = value;
}
},
enumerable: true,
configurable: true
});
BABYLON2.Scene.prototype.enableGeometryBufferRenderer = function(ratio) {
if (ratio === void 0) {
ratio = 1;
}
if (this._geometryBufferRenderer) {
return this._geometryBufferRenderer;
}
this._geometryBufferRenderer = new BABYLON2.GeometryBufferRenderer(this, ratio);
if (!this._geometryBufferRenderer.isSupported) {
this._geometryBufferRenderer = null;
}
return this._geometryBufferRenderer;
};
BABYLON2.Scene.prototype.disableGeometryBufferRenderer = function() {
if (!this._geometryBufferRenderer) {
return;
}
this._geometryBufferRenderer.dispose();
this._geometryBufferRenderer = null;
};
var GeometryBufferRendererSceneComponent = (
/** @class */
function() {
function GeometryBufferRendererSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
this.scene = scene;
}
GeometryBufferRendererSceneComponent2.prototype.register = function() {
this.scene._gatherRenderTargetsStage.registerStep(BABYLON2.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
};
GeometryBufferRendererSceneComponent2.prototype.rebuild = function() {
};
GeometryBufferRendererSceneComponent2.prototype.dispose = function() {
};
GeometryBufferRendererSceneComponent2.prototype._gatherRenderTargets = function(renderTargets) {
if (this.scene._geometryBufferRenderer) {
renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
}
};
return GeometryBufferRendererSceneComponent2;
}()
);
BABYLON2.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SSAORenderingPipeline = (
/** @class */
function(_super) {
__extends(SSAORenderingPipeline2, _super);
function SSAORenderingPipeline2(name, scene, ratio, cameras) {
var _this = _super.call(this, scene.getEngine(), name) || this;
_this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
_this.SSAORenderEffect = "SSAORenderEffect";
_this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
_this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
_this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
_this.totalStrength = 1;
_this.radius = 1e-4;
_this.area = 75e-4;
_this.fallOff = 1e-6;
_this.base = 0.5;
_this._firstUpdate = true;
_this._scene = scene;
_this._createRandomTexture();
_this._depthTexture = scene.enableDepthRenderer().getDepthMap();
var ssaoRatio = ratio.ssaoRatio || ratio;
var combineRatio = ratio.combineRatio || ratio;
_this._originalColorPostProcess = new BABYLON2.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
_this._createSSAOPostProcess(ssaoRatio);
_this._createBlurPostProcess(ssaoRatio);
_this._createSSAOCombinePostProcess(combineRatio);
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function() {
return _this._originalColorPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function() {
return _this._ssaoPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function() {
return _this._blurHPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function() {
return _this._blurVPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function() {
return _this._ssaoCombinePostProcess;
}, true));
scene.postProcessRenderPipelineManager.addPipeline(_this);
if (cameras) {
scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
}
return _this;
}
SSAORenderingPipeline2.prototype.dispose = function(disableDepthRender) {
if (disableDepthRender === void 0) {
disableDepthRender = false;
}
for (var i2 = 0; i2 < this._scene.cameras.length; i2++) {
var camera2 = this._scene.cameras[i2];
this._originalColorPostProcess.dispose(camera2);
this._ssaoPostProcess.dispose(camera2);
this._blurHPostProcess.dispose(camera2);
this._blurVPostProcess.dispose(camera2);
this._ssaoCombinePostProcess.dispose(camera2);
}
this._randomTexture.dispose();
if (disableDepthRender) {
this._scene.disableDepthRenderer();
}
this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
_super.prototype.dispose.call(this);
};
SSAORenderingPipeline2.prototype._createBlurPostProcess = function(ratio) {
var _this = this;
var size = 16;
this._blurHPostProcess = new BABYLON2.BlurPostProcess("BlurH", new BABYLON2.Vector2(1, 0), size, ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this._blurVPostProcess = new BABYLON2.BlurPostProcess("BlurV", new BABYLON2.Vector2(0, 1), size, ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this._blurHPostProcess.onActivateObservable.add(function() {
var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
_this._blurHPostProcess.kernel = size * dw;
});
this._blurVPostProcess.onActivateObservable.add(function() {
var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
_this._blurVPostProcess.kernel = size * dw;
});
};
SSAORenderingPipeline2.prototype._rebuild = function() {
this._firstUpdate = true;
_super.prototype._rebuild.call(this);
};
SSAORenderingPipeline2.prototype._createSSAOPostProcess = function(ratio) {
var _this = this;
var numSamples = 16;
var sampleSphere = [
0.5381,
0.1856,
-0.4319,
0.1379,
0.2486,
0.443,
0.3371,
0.5679,
-57e-4,
-0.6999,
-0.0451,
-19e-4,
0.0689,
-0.1598,
-0.8547,
0.056,
69e-4,
-0.1843,
-0.0146,
0.1402,
0.0762,
0.01,
-0.1924,
-0.0344,
-0.3577,
-0.5301,
-0.4358,
-0.3169,
0.1063,
0.0158,
0.0103,
-0.5869,
46e-4,
-0.0897,
-0.494,
0.3287,
0.7119,
-0.0154,
-0.0918,
-0.0533,
0.0596,
-0.5411,
0.0352,
-0.0631,
0.546,
-0.4776,
0.2847,
-0.0271
];
var samplesFactor = 1 / numSamples;
this._ssaoPostProcess = new BABYLON2.PostProcess("ssao", "ssao", [
"sampleSphere",
"samplesFactor",
"randTextureTiles",
"totalStrength",
"radius",
"area",
"fallOff",
"base",
"range",
"viewport"
], ["randomSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
this._ssaoPostProcess.onApply = function(effect) {
if (_this._firstUpdate) {
effect.setArray3("sampleSphere", sampleSphere);
effect.setFloat("samplesFactor", samplesFactor);
effect.setFloat("randTextureTiles", 4);
}
effect.setFloat("totalStrength", _this.totalStrength);
effect.setFloat("radius", _this.radius);
effect.setFloat("area", _this.area);
effect.setFloat("fallOff", _this.fallOff);
effect.setFloat("base", _this.base);
effect.setTexture("textureSampler", _this._depthTexture);
effect.setTexture("randomSampler", _this._randomTexture);
};
};
SSAORenderingPipeline2.prototype._createSSAOCombinePostProcess = function(ratio) {
var _this = this;
this._ssaoCombinePostProcess = new BABYLON2.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
this._ssaoCombinePostProcess.onApply = function(effect) {
effect.setVector4("viewport", BABYLON2.Tmp.Vector4[0].copyFromFloats(0, 0, 1, 1));
effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
};
};
SSAORenderingPipeline2.prototype._createRandomTexture = function() {
var size = 512;
this._randomTexture = new BABYLON2.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON2.Texture.TRILINEAR_SAMPLINGMODE);
this._randomTexture.wrapU = BABYLON2.Texture.WRAP_ADDRESSMODE;
this._randomTexture.wrapV = BABYLON2.Texture.WRAP_ADDRESSMODE;
var context = this._randomTexture.getContext();
var rand = function(min, max) {
return Math.random() * (max - min) + min;
};
var randVector = BABYLON2.Vector3.Zero();
for (var x = 0; x < size; x++) {
for (var y = 0; y < size; y++) {
randVector.x = Math.floor(rand(-1, 1) * 255);
randVector.y = Math.floor(rand(-1, 1) * 255);
randVector.z = Math.floor(rand(-1, 1) * 255);
context.fillStyle = "rgb(" + randVector.x + ", " + randVector.y + ", " + randVector.z + ")";
context.fillRect(x, y, 1, 1);
}
}
this._randomTexture.update(false);
};
__decorate([
BABYLON2.serialize()
], SSAORenderingPipeline2.prototype, "totalStrength", void 0);
__decorate([
BABYLON2.serialize()
], SSAORenderingPipeline2.prototype, "radius", void 0);
__decorate([
BABYLON2.serialize()
], SSAORenderingPipeline2.prototype, "area", void 0);
__decorate([
BABYLON2.serialize()
], SSAORenderingPipeline2.prototype, "fallOff", void 0);
__decorate([
BABYLON2.serialize()
], SSAORenderingPipeline2.prototype, "base", void 0);
return SSAORenderingPipeline2;
}(BABYLON2.PostProcessRenderPipeline)
);
BABYLON2.SSAORenderingPipeline = SSAORenderingPipeline;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SSAO2RenderingPipeline = (
/** @class */
function(_super) {
__extends(SSAO2RenderingPipeline2, _super);
function SSAO2RenderingPipeline2(name, scene, ratio, cameras) {
var _this = _super.call(this, scene.getEngine(), name) || this;
_this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
_this.SSAORenderEffect = "SSAORenderEffect";
_this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
_this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
_this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
_this.totalStrength = 1;
_this.maxZ = 100;
_this.minZAspect = 0.2;
_this._samples = 8;
_this._textureSamples = 1;
_this._expensiveBlur = true;
_this.radius = 2;
_this.base = 0;
_this._firstUpdate = true;
_this._bits = new Uint32Array(1);
_this._scene = scene;
_this._ratio = ratio;
if (!_this.isSupported) {
BABYLON2.Tools.Error("SSAO 2 needs WebGL 2 support.");
return _this;
}
var ssaoRatio = _this._ratio.ssaoRatio || ratio;
var blurRatio = _this._ratio.blurRatio || ratio;
var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
_this._createRandomTexture();
_this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
_this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
_this._originalColorPostProcess = new BABYLON2.PassPostProcess("SSAOOriginalSceneColor", 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
_this._originalColorPostProcess.samples = _this.textureSamples;
_this._createSSAOPostProcess(1);
_this._createBlurPostProcess(ssaoRatio, blurRatio);
_this._createSSAOCombinePostProcess(blurRatio);
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function() {
return _this._originalColorPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function() {
return _this._ssaoPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function() {
return _this._blurHPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function() {
return _this._blurVPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function() {
return _this._ssaoCombinePostProcess;
}, true));
scene.postProcessRenderPipelineManager.addPipeline(_this);
if (cameras) {
scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
}
return _this;
}
Object.defineProperty(SSAO2RenderingPipeline2.prototype, "samples", {
get: function() {
return this._samples;
},
/**
* Number of samples used for the SSAO calculations. Default value is 8
*/
set: function(n) {
this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
this._samples = n;
this._sampleSphere = this._generateHemisphere();
this._firstUpdate = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SSAO2RenderingPipeline2.prototype, "textureSamples", {
get: function() {
return this._textureSamples;
},
/**
* Number of samples to use for antialiasing
*/
set: function(n) {
this._textureSamples = n;
this._originalColorPostProcess.samples = n;
this._blurHPostProcess.samples = n;
this._blurVPostProcess.samples = n;
this._ssaoPostProcess.samples = n;
this._ssaoCombinePostProcess.samples = n;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SSAO2RenderingPipeline2.prototype, "expensiveBlur", {
get: function() {
return this._expensiveBlur;
},
/**
* If bilateral blur should be used
*/
set: function(b2) {
this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b2 ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b2 ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
this._expensiveBlur = b2;
this._firstUpdate = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SSAO2RenderingPipeline2, "IsSupported", {
/**
* Support test.
*/
get: function() {
var engine = BABYLON2.Engine.LastCreatedEngine;
if (!engine) {
return false;
}
return engine.getCaps().drawBuffersExtension;
},
enumerable: true,
configurable: true
});
SSAO2RenderingPipeline2.prototype.dispose = function(disableGeometryBufferRenderer) {
if (disableGeometryBufferRenderer === void 0) {
disableGeometryBufferRenderer = false;
}
for (var i2 = 0; i2 < this._scene.cameras.length; i2++) {
var camera2 = this._scene.cameras[i2];
this._originalColorPostProcess.dispose(camera2);
this._ssaoPostProcess.dispose(camera2);
this._blurHPostProcess.dispose(camera2);
this._blurVPostProcess.dispose(camera2);
this._ssaoCombinePostProcess.dispose(camera2);
}
this._randomTexture.dispose();
if (disableGeometryBufferRenderer) {
this._scene.disableGeometryBufferRenderer();
}
this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
_super.prototype.dispose.call(this);
};
SSAO2RenderingPipeline2.prototype._createBlurPostProcess = function(ssaoRatio, blurRatio) {
var _this = this;
this._samplerOffsets = [];
var expensive = this.expensiveBlur;
for (var i2 = -8; i2 < 8; i2++) {
this._samplerOffsets.push(i2 * 2 + 0.5);
}
this._blurHPostProcess = new BABYLON2.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON2.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
this._blurHPostProcess.onApply = function(effect) {
if (!_this._scene.activeCamera) {
return;
}
effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
effect.setFloat("near", _this._scene.activeCamera.minZ);
effect.setFloat("far", _this._scene.activeCamera.maxZ);
effect.setFloat("radius", _this.radius);
effect.setTexture("depthSampler", _this._depthTexture);
if (_this._firstUpdate) {
effect.setArray("samplerOffsets", _this._samplerOffsets);
}
};
this._blurVPostProcess = new BABYLON2.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON2.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
this._blurVPostProcess.onApply = function(effect) {
if (!_this._scene.activeCamera) {
return;
}
effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
effect.setFloat("near", _this._scene.activeCamera.minZ);
effect.setFloat("far", _this._scene.activeCamera.maxZ);
effect.setFloat("radius", _this.radius);
effect.setTexture("depthSampler", _this._depthTexture);
if (_this._firstUpdate) {
effect.setArray("samplerOffsets", _this._samplerOffsets);
_this._firstUpdate = false;
}
};
this._blurHPostProcess.samples = this.textureSamples;
this._blurVPostProcess.samples = this.textureSamples;
};
SSAO2RenderingPipeline2.prototype._rebuild = function() {
this._firstUpdate = true;
_super.prototype._rebuild.call(this);
};
SSAO2RenderingPipeline2.prototype._radicalInverse_VdC = function(i2) {
this._bits[0] = i2;
this._bits[0] = (this._bits[0] << 16 | this._bits[0] >> 16) >>> 0;
this._bits[0] = (this._bits[0] & 1431655765) << 1 | (this._bits[0] & 2863311530) >>> 1 >>> 0;
this._bits[0] = (this._bits[0] & 858993459) << 2 | (this._bits[0] & 3435973836) >>> 2 >>> 0;
this._bits[0] = (this._bits[0] & 252645135) << 4 | (this._bits[0] & 4042322160) >>> 4 >>> 0;
this._bits[0] = (this._bits[0] & 16711935) << 8 | (this._bits[0] & 4278255360) >>> 8 >>> 0;
return this._bits[0] * 23283064365386963e-26;
};
SSAO2RenderingPipeline2.prototype._hammersley = function(i2, n) {
return [i2 / n, this._radicalInverse_VdC(i2)];
};
SSAO2RenderingPipeline2.prototype._hemisphereSample_uniform = function(u, v) {
var phi = v * 2 * Math.PI;
var cosTheta = 1 - (u * 0.85 + 0.15);
var sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
return new BABYLON2.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
};
SSAO2RenderingPipeline2.prototype._generateHemisphere = function() {
var numSamples = this.samples;
var result = [];
var vector;
var i2 = 0;
while (i2 < numSamples) {
if (numSamples < 16) {
vector = this._hemisphereSample_uniform(Math.random(), Math.random());
} else {
var rand = this._hammersley(i2, numSamples);
vector = this._hemisphereSample_uniform(rand[0], rand[1]);
}
result.push(vector.x, vector.y, vector.z);
i2++;
}
return result;
};
SSAO2RenderingPipeline2.prototype._createSSAOPostProcess = function(ratio) {
var _this = this;
var numSamples = this.samples;
this._sampleSphere = this._generateHemisphere();
this._ssaoPostProcess = new BABYLON2.PostProcess("ssao2", "ssao2", [
"sampleSphere",
"samplesFactor",
"randTextureTiles",
"totalStrength",
"radius",
"base",
"range",
"projection",
"near",
"far",
"texelSize",
"xViewport",
"yViewport",
"maxZ",
"minZAspect"
], ["randomSampler", "normalSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
this._ssaoPostProcess.onApply = function(effect) {
if (_this._firstUpdate) {
effect.setArray3("sampleSphere", _this._sampleSphere);
effect.setFloat("randTextureTiles", 32);
}
if (!_this._scene.activeCamera) {
return;
}
effect.setFloat("samplesFactor", 1 / _this.samples);
effect.setFloat("totalStrength", _this.totalStrength);
effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
effect.setFloat("radius", _this.radius);
effect.setFloat("maxZ", _this.maxZ);
effect.setFloat("minZAspect", _this.minZAspect);
effect.setFloat("base", _this.base);
effect.setFloat("near", _this._scene.activeCamera.minZ);
effect.setFloat("far", _this._scene.activeCamera.maxZ);
effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
effect.setMatrix("projection", _this._scene.getProjectionMatrix());
effect.setTexture("textureSampler", _this._depthTexture);
effect.setTexture("normalSampler", _this._normalTexture);
effect.setTexture("randomSampler", _this._randomTexture);
};
this._ssaoPostProcess.samples = this.textureSamples;
};
SSAO2RenderingPipeline2.prototype._createSSAOCombinePostProcess = function(ratio) {
var _this = this;
this._ssaoCombinePostProcess = new BABYLON2.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
this._ssaoCombinePostProcess.onApply = function(effect) {
var viewport = _this._scene.activeCamera.viewport;
effect.setVector4("viewport", BABYLON2.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
};
this._ssaoCombinePostProcess.samples = this.textureSamples;
};
SSAO2RenderingPipeline2.prototype._createRandomTexture = function() {
var size = 128;
this._randomTexture = new BABYLON2.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON2.Texture.TRILINEAR_SAMPLINGMODE);
this._randomTexture.wrapU = BABYLON2.Texture.WRAP_ADDRESSMODE;
this._randomTexture.wrapV = BABYLON2.Texture.WRAP_ADDRESSMODE;
var context = this._randomTexture.getContext();
var rand = function(min, max) {
return Math.random() * (max - min) + min;
};
var randVector = BABYLON2.Vector3.Zero();
for (var x = 0; x < size; x++) {
for (var y = 0; y < size; y++) {
randVector.x = rand(0, 1);
randVector.y = rand(0, 1);
randVector.z = 0;
randVector.normalize();
randVector.scaleInPlace(255);
randVector.x = Math.floor(randVector.x);
randVector.y = Math.floor(randVector.y);
context.fillStyle = "rgb(" + randVector.x + ", " + randVector.y + ", " + randVector.z + ")";
context.fillRect(x, y, 1, 1);
}
}
this._randomTexture.update(false);
};
SSAO2RenderingPipeline2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "SSAO2RenderingPipeline";
return serializationObject;
};
SSAO2RenderingPipeline2.Parse = function(source, scene, rootUrl) {
return BABYLON2.SerializationHelper.Parse(function() {
return new SSAO2RenderingPipeline2(source._name, scene, source._ratio);
}, source, scene, rootUrl);
};
__decorate([
BABYLON2.serialize()
], SSAO2RenderingPipeline2.prototype, "totalStrength", void 0);
__decorate([
BABYLON2.serialize()
], SSAO2RenderingPipeline2.prototype, "maxZ", void 0);
__decorate([
BABYLON2.serialize()
], SSAO2RenderingPipeline2.prototype, "minZAspect", void 0);
__decorate([
BABYLON2.serialize("samples")
], SSAO2RenderingPipeline2.prototype, "_samples", void 0);
__decorate([
BABYLON2.serialize("textureSamples")
], SSAO2RenderingPipeline2.prototype, "_textureSamples", void 0);
__decorate([
BABYLON2.serialize()
], SSAO2RenderingPipeline2.prototype, "_ratio", void 0);
__decorate([
BABYLON2.serialize("expensiveBlur")
], SSAO2RenderingPipeline2.prototype, "_expensiveBlur", void 0);
__decorate([
BABYLON2.serialize()
], SSAO2RenderingPipeline2.prototype, "radius", void 0);
__decorate([
BABYLON2.serialize()
], SSAO2RenderingPipeline2.prototype, "base", void 0);
return SSAO2RenderingPipeline2;
}(BABYLON2.PostProcessRenderPipeline)
);
BABYLON2.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var LensRenderingPipeline = (
/** @class */
function(_super) {
__extends(LensRenderingPipeline2, _super);
function LensRenderingPipeline2(name, parameters, scene, ratio, cameras) {
if (ratio === void 0) {
ratio = 1;
}
var _this = _super.call(this, scene.getEngine(), name) || this;
_this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
_this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
_this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
_this._scene = scene;
_this._depthTexture = scene.enableDepthRenderer().getDepthMap();
if (parameters.grain_texture) {
_this._grainTexture = parameters.grain_texture;
} else {
_this._createGrainTexture();
}
_this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
_this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
_this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
_this._distortion = parameters.distortion ? parameters.distortion : 0;
_this._highlightsGain = parameters.dof_gain !== void 0 ? parameters.dof_gain : -1;
_this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
_this._dofDistance = parameters.dof_focus_distance !== void 0 ? parameters.dof_focus_distance : -1;
_this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
_this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
_this._dofPentagon = parameters.dof_pentagon !== void 0 ? parameters.dof_pentagon : true;
_this._blurNoise = parameters.blur_noise !== void 0 ? parameters.blur_noise : true;
_this._createChromaticAberrationPostProcess(ratio);
_this._createHighlightsPostProcess(ratio);
_this._createDepthOfFieldPostProcess(ratio / 4);
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function() {
return _this._chromaticAberrationPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function() {
return _this._highlightsPostProcess;
}, true));
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function() {
return _this._depthOfFieldPostProcess;
}, true));
if (_this._highlightsGain === -1) {
_this._disableEffect(_this.HighlightsEnhancingEffect, null);
}
scene.postProcessRenderPipelineManager.addPipeline(_this);
if (cameras) {
scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
}
return _this;
}
LensRenderingPipeline2.prototype.setEdgeBlur = function(amount) {
this._edgeBlur = amount;
};
LensRenderingPipeline2.prototype.disableEdgeBlur = function() {
this._edgeBlur = 0;
};
LensRenderingPipeline2.prototype.setGrainAmount = function(amount) {
this._grainAmount = amount;
};
LensRenderingPipeline2.prototype.disableGrain = function() {
this._grainAmount = 0;
};
LensRenderingPipeline2.prototype.setChromaticAberration = function(amount) {
this._chromaticAberration = amount;
};
LensRenderingPipeline2.prototype.disableChromaticAberration = function() {
this._chromaticAberration = 0;
};
LensRenderingPipeline2.prototype.setEdgeDistortion = function(amount) {
this._distortion = amount;
};
LensRenderingPipeline2.prototype.disableEdgeDistortion = function() {
this._distortion = 0;
};
LensRenderingPipeline2.prototype.setFocusDistance = function(amount) {
this._dofDistance = amount;
};
LensRenderingPipeline2.prototype.disableDepthOfField = function() {
this._dofDistance = -1;
};
LensRenderingPipeline2.prototype.setAperture = function(amount) {
this._dofAperture = amount;
};
LensRenderingPipeline2.prototype.setDarkenOutOfFocus = function(amount) {
this._dofDarken = amount;
};
LensRenderingPipeline2.prototype.enablePentagonBokeh = function() {
this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
};
LensRenderingPipeline2.prototype.disablePentagonBokeh = function() {
this._highlightsPostProcess.updateEffect();
};
LensRenderingPipeline2.prototype.enableNoiseBlur = function() {
this._blurNoise = true;
};
LensRenderingPipeline2.prototype.disableNoiseBlur = function() {
this._blurNoise = false;
};
LensRenderingPipeline2.prototype.setHighlightsGain = function(amount) {
this._highlightsGain = amount;
};
LensRenderingPipeline2.prototype.setHighlightsThreshold = function(amount) {
if (this._highlightsGain === -1) {
this._highlightsGain = 1;
}
this._highlightsThreshold = amount;
};
LensRenderingPipeline2.prototype.disableHighlights = function() {
this._highlightsGain = -1;
};
LensRenderingPipeline2.prototype.dispose = function(disableDepthRender) {
if (disableDepthRender === void 0) {
disableDepthRender = false;
}
this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
this._chromaticAberrationPostProcess = null;
this._highlightsPostProcess = null;
this._depthOfFieldPostProcess = null;
this._grainTexture.dispose();
if (disableDepthRender) {
this._scene.disableDepthRenderer();
}
};
LensRenderingPipeline2.prototype._createChromaticAberrationPostProcess = function(ratio) {
var _this = this;
this._chromaticAberrationPostProcess = new BABYLON2.PostProcess(
"LensChromaticAberration",
"chromaticAberration",
["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"],
// uniforms
[],
// samplers
ratio,
null,
BABYLON2.Texture.TRILINEAR_SAMPLINGMODE,
this._scene.getEngine(),
false
);
this._chromaticAberrationPostProcess.onApply = function(effect) {
effect.setFloat("chromatic_aberration", _this._chromaticAberration);
effect.setFloat("screen_width", _this._scene.getEngine().getRenderWidth());
effect.setFloat("screen_height", _this._scene.getEngine().getRenderHeight());
effect.setFloat("radialIntensity", 1);
effect.setFloat2("direction", 17, 17);
effect.setFloat2("centerPosition", 0.5, 0.5);
};
};
LensRenderingPipeline2.prototype._createHighlightsPostProcess = function(ratio) {
var _this = this;
this._highlightsPostProcess = new BABYLON2.PostProcess(
"LensHighlights",
"lensHighlights",
["gain", "threshold", "screen_width", "screen_height"],
// uniforms
[],
// samplers
ratio,
null,
BABYLON2.Texture.TRILINEAR_SAMPLINGMODE,
this._scene.getEngine(),
false,
this._dofPentagon ? "#define PENTAGON\n" : ""
);
this._highlightsPostProcess.onApply = function(effect) {
effect.setFloat("gain", _this._highlightsGain);
effect.setFloat("threshold", _this._highlightsThreshold);
effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
effect.setFloat("screen_width", _this._scene.getEngine().getRenderWidth());
effect.setFloat("screen_height", _this._scene.getEngine().getRenderHeight());
};
};
LensRenderingPipeline2.prototype._createDepthOfFieldPostProcess = function(ratio) {
var _this = this;
this._depthOfFieldPostProcess = new BABYLON2.PostProcess("LensDepthOfField", "depthOfField", [
"grain_amount",
"blur_noise",
"screen_width",
"screen_height",
"distortion",
"dof_enabled",
"screen_distance",
"aperture",
"darken",
"edge_blur",
"highlights",
"near",
"far"
], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON2.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
this._depthOfFieldPostProcess.onApply = function(effect) {
effect.setTexture("depthSampler", _this._depthTexture);
effect.setTexture("grainSampler", _this._grainTexture);
effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
effect.setFloat("grain_amount", _this._grainAmount);
effect.setBool("blur_noise", _this._blurNoise);
effect.setFloat("screen_width", _this._scene.getEngine().getRenderWidth());
effect.setFloat("screen_height", _this._scene.getEngine().getRenderHeight());
effect.setFloat("distortion", _this._distortion);
effect.setBool("dof_enabled", _this._dofDistance !== -1);
effect.setFloat("screen_distance", 1 / (0.1 - 1 / _this._dofDistance));
effect.setFloat("aperture", _this._dofAperture);
effect.setFloat("darken", _this._dofDarken);
effect.setFloat("edge_blur", _this._edgeBlur);
effect.setBool("highlights", _this._highlightsGain !== -1);
if (_this._scene.activeCamera) {
effect.setFloat("near", _this._scene.activeCamera.minZ);
effect.setFloat("far", _this._scene.activeCamera.maxZ);
}
};
};
LensRenderingPipeline2.prototype._createGrainTexture = function() {
var size = 512;
this._grainTexture = new BABYLON2.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
this._grainTexture.wrapU = BABYLON2.Texture.WRAP_ADDRESSMODE;
this._grainTexture.wrapV = BABYLON2.Texture.WRAP_ADDRESSMODE;
var context = this._grainTexture.getContext();
var rand = function(min, max) {
return Math.random() * (max - min) + min;
};
var value;
for (var x = 0; x < size; x++) {
for (var y = 0; y < size; y++) {
value = Math.floor(rand(0.42, 0.58) * 255);
context.fillStyle = "rgb(" + value + ", " + value + ", " + value + ")";
context.fillRect(x, y, 1, 1);
}
}
this._grainTexture.update(false);
};
return LensRenderingPipeline2;
}(BABYLON2.PostProcessRenderPipeline)
);
BABYLON2.LensRenderingPipeline = LensRenderingPipeline;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var StandardRenderingPipeline = (
/** @class */
function(_super) {
__extends(StandardRenderingPipeline2, _super);
function StandardRenderingPipeline2(name, scene, ratio, originalPostProcess, cameras) {
if (originalPostProcess === void 0) {
originalPostProcess = null;
}
var _this = _super.call(this, scene.getEngine(), name) || this;
_this.downSampleX4PostProcess = null;
_this.brightPassPostProcess = null;
_this.blurHPostProcesses = [];
_this.blurVPostProcesses = [];
_this.textureAdderPostProcess = null;
_this.volumetricLightPostProcess = null;
_this.volumetricLightSmoothXPostProcess = null;
_this.volumetricLightSmoothYPostProcess = null;
_this.volumetricLightMergePostProces = null;
_this.volumetricLightFinalPostProcess = null;
_this.luminancePostProcess = null;
_this.luminanceDownSamplePostProcesses = [];
_this.hdrPostProcess = null;
_this.textureAdderFinalPostProcess = null;
_this.lensFlareFinalPostProcess = null;
_this.hdrFinalPostProcess = null;
_this.lensFlarePostProcess = null;
_this.lensFlareComposePostProcess = null;
_this.motionBlurPostProcess = null;
_this.depthOfFieldPostProcess = null;
_this.fxaaPostProcess = null;
_this.brightThreshold = 1;
_this.blurWidth = 512;
_this.horizontalBlur = false;
_this.exposure = 1;
_this.lensTexture = null;
_this.volumetricLightCoefficient = 0.2;
_this.volumetricLightPower = 4;
_this.volumetricLightBlurScale = 64;
_this.sourceLight = null;
_this.hdrMinimumLuminance = 1;
_this.hdrDecreaseRate = 0.5;
_this.hdrIncreaseRate = 0.5;
_this.lensColorTexture = null;
_this.lensFlareStrength = 20;
_this.lensFlareGhostDispersal = 1.4;
_this.lensFlareHaloWidth = 0.7;
_this.lensFlareDistortionStrength = 16;
_this.lensStarTexture = null;
_this.lensFlareDirtTexture = null;
_this.depthOfFieldDistance = 10;
_this.depthOfFieldBlurWidth = 64;
_this.motionStrength = 1;
_this.animations = [];
_this._currentDepthOfFieldSource = null;
_this._hdrCurrentLuminance = 1;
_this._bloomEnabled = false;
_this._depthOfFieldEnabled = false;
_this._vlsEnabled = false;
_this._lensFlareEnabled = false;
_this._hdrEnabled = false;
_this._motionBlurEnabled = false;
_this._fxaaEnabled = false;
_this._motionBlurSamples = 64;
_this._volumetricLightStepsCount = 50;
_this._samples = 1;
_this._cameras = cameras || [];
_this._scene = scene;
_this._basePostProcess = originalPostProcess;
_this._ratio = ratio;
_this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON2.Engine.TEXTURETYPE_FLOAT : BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
scene.postProcessRenderPipelineManager.addPipeline(_this);
_this._buildPipeline();
return _this;
}
Object.defineProperty(StandardRenderingPipeline2.prototype, "BloomEnabled", {
/**
* @ignore
* Specifies if the bloom pipeline is enabled
*/
get: function() {
return this._bloomEnabled;
},
set: function(enabled) {
if (this._bloomEnabled === enabled) {
return;
}
this._bloomEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "DepthOfFieldEnabled", {
/**
* @ignore
* Specifies if the depth of field pipeline is enabed
*/
get: function() {
return this._depthOfFieldEnabled;
},
set: function(enabled) {
if (this._depthOfFieldEnabled === enabled) {
return;
}
this._depthOfFieldEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "LensFlareEnabled", {
/**
* @ignore
* Specifies if the lens flare pipeline is enabed
*/
get: function() {
return this._lensFlareEnabled;
},
set: function(enabled) {
if (this._lensFlareEnabled === enabled) {
return;
}
this._lensFlareEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "HDREnabled", {
/**
* @ignore
* Specifies if the HDR pipeline is enabled
*/
get: function() {
return this._hdrEnabled;
},
set: function(enabled) {
if (this._hdrEnabled === enabled) {
return;
}
this._hdrEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "VLSEnabled", {
/**
* @ignore
* Specifies if the volumetric lights scattering effect is enabled
*/
get: function() {
return this._vlsEnabled;
},
set: function(enabled) {
if (this._vlsEnabled === enabled) {
return;
}
if (enabled) {
var geometry = this._scene.enableGeometryBufferRenderer();
if (!geometry) {
BABYLON2.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
return;
}
}
this._vlsEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "MotionBlurEnabled", {
/**
* @ignore
* Specifies if the motion blur effect is enabled
*/
get: function() {
return this._motionBlurEnabled;
},
set: function(enabled) {
if (this._motionBlurEnabled === enabled) {
return;
}
this._motionBlurEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "fxaaEnabled", {
/**
* Specifies if anti-aliasing is enabled
*/
get: function() {
return this._fxaaEnabled;
},
set: function(enabled) {
if (this._fxaaEnabled === enabled) {
return;
}
this._fxaaEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "volumetricLightStepsCount", {
/**
* Specifies the number of steps used to calculate the volumetric lights
* Typically in interval [50, 200]
*/
get: function() {
return this._volumetricLightStepsCount;
},
set: function(count) {
if (this.volumetricLightPostProcess) {
this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
}
this._volumetricLightStepsCount = count;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "motionBlurSamples", {
/**
* Specifies the number of samples used for the motion blur effect
* Typically in interval [16, 64]
*/
get: function() {
return this._motionBlurSamples;
},
set: function(samples) {
if (this.motionBlurPostProcess) {
this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
}
this._motionBlurSamples = samples;
},
enumerable: true,
configurable: true
});
Object.defineProperty(StandardRenderingPipeline2.prototype, "samples", {
/**
* Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
*/
get: function() {
return this._samples;
},
set: function(sampleCount) {
if (this._samples === sampleCount) {
return;
}
this._samples = sampleCount;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
StandardRenderingPipeline2.prototype._buildPipeline = function() {
var _this = this;
var ratio = this._ratio;
var scene = this._scene;
this._disposePostProcesses();
this._reset();
if (!this._basePostProcess) {
this.originalPostProcess = new BABYLON2.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
this.originalPostProcess.onApply = function(effect) {
_this._currentDepthOfFieldSource = _this.originalPostProcess;
};
} else {
this.originalPostProcess = this._basePostProcess;
}
if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function() {
return _this.originalPostProcess;
}, true));
}
this._currentDepthOfFieldSource = this.originalPostProcess;
if (this._bloomEnabled) {
this._createDownSampleX4PostProcess(scene, ratio / 2);
this._createBrightPassPostProcess(scene, ratio / 2);
this._createBlurPostProcesses(scene, ratio / 4, 1);
this._createTextureAdderPostProcess(scene, ratio);
this.textureAdderFinalPostProcess = new BABYLON2.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function() {
return _this.textureAdderFinalPostProcess;
}, true));
}
if (this._vlsEnabled) {
this._createVolumetricLightPostProcess(scene, ratio);
this.volumetricLightFinalPostProcess = new BABYLON2.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function() {
return _this.volumetricLightFinalPostProcess;
}, true));
}
if (this._lensFlareEnabled) {
this._createLensFlarePostProcess(scene, ratio);
this.lensFlareFinalPostProcess = new BABYLON2.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function() {
return _this.lensFlareFinalPostProcess;
}, true));
}
if (this._hdrEnabled) {
this._createLuminancePostProcesses(scene, this._floatTextureType);
this._createHdrPostProcess(scene, ratio);
this.hdrFinalPostProcess = new BABYLON2.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function() {
return _this.hdrFinalPostProcess;
}, true));
}
if (this._depthOfFieldEnabled) {
this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
this._createDepthOfFieldPostProcess(scene, ratio);
}
if (this._motionBlurEnabled) {
this._createMotionBlurPostProcess(scene, ratio);
}
if (this._fxaaEnabled) {
this.fxaaPostProcess = new BABYLON2.FxaaPostProcess("fxaa", 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function() {
return _this.fxaaPostProcess;
}, true));
}
if (this._cameras !== null) {
this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
}
if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
BABYLON2.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
}
};
StandardRenderingPipeline2.prototype._createDownSampleX4PostProcess = function(scene, ratio) {
var _this = this;
var downSampleX4Offsets = new Array(32);
this.downSampleX4PostProcess = new BABYLON2.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.downSampleX4PostProcess.onApply = function(effect) {
var id = 0;
var width = _this.downSampleX4PostProcess.width;
var height = _this.downSampleX4PostProcess.height;
for (var i2 = -2; i2 < 2; i2++) {
for (var j = -2; j < 2; j++) {
downSampleX4Offsets[id] = (i2 + 0.5) * (1 / width);
downSampleX4Offsets[id + 1] = (j + 0.5) * (1 / height);
id += 2;
}
}
effect.setArray2("dsOffsets", downSampleX4Offsets);
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function() {
return _this.downSampleX4PostProcess;
}, true));
};
StandardRenderingPipeline2.prototype._createBrightPassPostProcess = function(scene, ratio) {
var _this = this;
var brightOffsets = new Array(8);
this.brightPassPostProcess = new BABYLON2.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.brightPassPostProcess.onApply = function(effect) {
var sU = 1 / _this.brightPassPostProcess.width;
var sV = 1 / _this.brightPassPostProcess.height;
brightOffsets[0] = -0.5 * sU;
brightOffsets[1] = 0.5 * sV;
brightOffsets[2] = 0.5 * sU;
brightOffsets[3] = 0.5 * sV;
brightOffsets[4] = -0.5 * sU;
brightOffsets[5] = -0.5 * sV;
brightOffsets[6] = 0.5 * sU;
brightOffsets[7] = -0.5 * sV;
effect.setArray2("dsOffsets", brightOffsets);
effect.setFloat("brightThreshold", _this.brightThreshold);
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function() {
return _this.brightPassPostProcess;
}, true));
};
StandardRenderingPipeline2.prototype._createBlurPostProcesses = function(scene, ratio, indice, blurWidthKey) {
var _this = this;
if (blurWidthKey === void 0) {
blurWidthKey = "blurWidth";
}
var engine = scene.getEngine();
var blurX = new BABYLON2.BlurPostProcess("HDRBlurH_" + indice, new BABYLON2.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
var blurY = new BABYLON2.BlurPostProcess("HDRBlurV_" + indice, new BABYLON2.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
blurX.onActivateObservable.add(function() {
var dw = blurX.width / engine.getRenderWidth();
blurX.kernel = _this[blurWidthKey] * dw;
});
blurY.onActivateObservable.add(function() {
var dw = blurY.height / engine.getRenderHeight();
blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
});
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function() {
return blurX;
}, true));
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function() {
return blurY;
}, true));
this.blurHPostProcesses.push(blurX);
this.blurVPostProcesses.push(blurY);
};
StandardRenderingPipeline2.prototype._createTextureAdderPostProcess = function(scene, ratio) {
var _this = this;
this.textureAdderPostProcess = new BABYLON2.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.textureAdderPostProcess.onApply = function(effect) {
effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
effect.setTexture("lensSampler", _this.lensTexture);
effect.setFloat("exposure", _this.exposure);
_this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function() {
return _this.textureAdderPostProcess;
}, true));
};
StandardRenderingPipeline2.prototype._createVolumetricLightPostProcess = function(scene, ratio) {
var _this = this;
var geometryRenderer = scene.enableGeometryBufferRenderer();
geometryRenderer.enablePosition = true;
var geometry = geometryRenderer.getGBuffer();
this.volumetricLightPostProcess = new BABYLON2.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
var depthValues = BABYLON2.Vector2.Zero();
this.volumetricLightPostProcess.onApply = function(effect) {
if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
var generator = _this.sourceLight.getShadowGenerator();
effect.setTexture("shadowMapSampler", generator.getShadowMap());
effect.setTexture("positionSampler", geometry.textures[2]);
effect.setColor3("sunColor", _this.sourceLight.diffuse);
effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
effect.setFloat("scatteringPower", _this.volumetricLightPower);
depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
effect.setVector2("depthValues", depthValues);
}
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function() {
return _this.volumetricLightPostProcess;
}, true));
this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
this.volumetricLightMergePostProces = new BABYLON2.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
this.volumetricLightMergePostProces.onApply = function(effect) {
effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
_this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function() {
return _this.volumetricLightMergePostProces;
}, true));
};
StandardRenderingPipeline2.prototype._createLuminancePostProcesses = function(scene, textureType) {
var _this = this;
var size = Math.pow(3, StandardRenderingPipeline2.LuminanceSteps);
this.luminancePostProcess = new BABYLON2.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
var offsets = [];
this.luminancePostProcess.onApply = function(effect) {
var sU = 1 / _this.luminancePostProcess.width;
var sV = 1 / _this.luminancePostProcess.height;
offsets[0] = -0.5 * sU;
offsets[1] = 0.5 * sV;
offsets[2] = 0.5 * sU;
offsets[3] = 0.5 * sV;
offsets[4] = -0.5 * sU;
offsets[5] = -0.5 * sV;
offsets[6] = 0.5 * sU;
offsets[7] = -0.5 * sV;
effect.setArray2("lumOffsets", offsets);
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function() {
return _this.luminancePostProcess;
}, true));
for (var i2 = StandardRenderingPipeline2.LuminanceSteps - 1; i2 >= 0; i2--) {
var size = Math.pow(3, i2);
var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
if (i2 === 0) {
defines += "#define FINAL_DOWN_SAMPLER";
}
var postProcess = new BABYLON2.PostProcess("HDRLuminanceDownSample" + i2, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
this.luminanceDownSamplePostProcesses.push(postProcess);
}
var lastLuminance = this.luminancePostProcess;
this.luminanceDownSamplePostProcesses.forEach(function(pp, index) {
var downSampleOffsets = new Array(18);
pp.onApply = function(effect) {
if (!lastLuminance) {
return;
}
var id = 0;
for (var x = -1; x < 2; x++) {
for (var y = -1; y < 2; y++) {
downSampleOffsets[id] = x / lastLuminance.width;
downSampleOffsets[id + 1] = y / lastLuminance.height;
id += 2;
}
}
effect.setArray2("dsOffsets", downSampleOffsets);
effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
lastLuminance = _this.luminancePostProcess;
} else {
lastLuminance = pp;
}
};
if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
pp.onAfterRender = function(effect) {
var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
var bit_shift = new BABYLON2.Vector4(1 / (255 * 255 * 255), 1 / (255 * 255), 1 / 255, 1);
_this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100;
};
}
_this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function() {
return pp;
}, true));
});
};
StandardRenderingPipeline2.prototype._createHdrPostProcess = function(scene, ratio) {
var _this = this;
this.hdrPostProcess = new BABYLON2.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
var outputLiminance = 1;
var time = 0;
var lastTime = 0;
this.hdrPostProcess.onApply = function(effect) {
effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
time += scene.getEngine().getDeltaTime();
if (outputLiminance < 0) {
outputLiminance = _this._hdrCurrentLuminance;
} else {
var dt = (lastTime - time) / 1e3;
if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
outputLiminance += _this.hdrDecreaseRate * dt;
} else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
outputLiminance -= _this.hdrIncreaseRate * dt;
} else {
outputLiminance = _this._hdrCurrentLuminance;
}
}
outputLiminance = BABYLON2.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
effect.setFloat("averageLuminance", outputLiminance);
lastTime = time;
_this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDR", function() {
return _this.hdrPostProcess;
}, true));
};
StandardRenderingPipeline2.prototype._createLensFlarePostProcess = function(scene, ratio) {
var _this = this;
this.lensFlarePostProcess = new BABYLON2.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function() {
return _this.lensFlarePostProcess;
}, true));
this._createBlurPostProcesses(scene, ratio / 4, 2);
this.lensFlareComposePostProcess = new BABYLON2.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function() {
return _this.lensFlareComposePostProcess;
}, true));
var resolution = new BABYLON2.Vector2(0, 0);
this.lensFlarePostProcess.onApply = function(effect) {
effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
effect.setTexture("lensColorSampler", _this.lensColorTexture);
effect.setFloat("strength", _this.lensFlareStrength);
effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
resolution.x = _this.lensFlarePostProcess.width;
resolution.y = _this.lensFlarePostProcess.height;
effect.setVector2("resolution", resolution);
effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
};
var scaleBias1 = BABYLON2.Matrix.FromValues(2, 0, -1, 0, 0, 2, -1, 0, 0, 0, 1, 0, 0, 0, 0, 1);
var scaleBias2 = BABYLON2.Matrix.FromValues(0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1, 0, 0, 0, 0, 1);
this.lensFlareComposePostProcess.onApply = function(effect) {
if (!_this._scene.activeCamera) {
return;
}
effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
effect.setTexture("lensStarSampler", _this.lensStarTexture);
var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
var camRot = BABYLON2.Vector3.Dot(camerax.toVector3(), new BABYLON2.Vector3(1, 0, 0)) + BABYLON2.Vector3.Dot(cameraz.toVector3(), new BABYLON2.Vector3(0, 0, 1));
camRot *= 4;
var starRotation = BABYLON2.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0, 0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
effect.setMatrix("lensStarMatrix", lensStarMatrix);
_this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
};
};
StandardRenderingPipeline2.prototype._createDepthOfFieldPostProcess = function(scene, ratio) {
var _this = this;
this.depthOfFieldPostProcess = new BABYLON2.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this.depthOfFieldPostProcess.onApply = function(effect) {
effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
effect.setTexture("depthSampler", _this._getDepthTexture());
effect.setFloat("distance", _this.depthOfFieldDistance);
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function() {
return _this.depthOfFieldPostProcess;
}, true));
};
StandardRenderingPipeline2.prototype._createMotionBlurPostProcess = function(scene, ratio) {
var _this = this;
this.motionBlurPostProcess = new BABYLON2.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
var motionScale = 0;
var prevViewProjection = BABYLON2.Matrix.Identity();
var invViewProjection = BABYLON2.Matrix.Identity();
var viewProjection = BABYLON2.Matrix.Identity();
var screenSize = BABYLON2.Vector2.Zero();
this.motionBlurPostProcess.onApply = function(effect) {
viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
viewProjection.invertToRef(invViewProjection);
effect.setMatrix("inverseViewProjection", invViewProjection);
effect.setMatrix("prevViewProjection", prevViewProjection);
prevViewProjection = viewProjection;
screenSize.x = _this.motionBlurPostProcess.width;
screenSize.y = _this.motionBlurPostProcess.height;
effect.setVector2("screenSize", screenSize);
motionScale = scene.getEngine().getFps() / 60;
effect.setFloat("motionScale", motionScale);
effect.setFloat("motionStrength", _this.motionStrength);
effect.setTexture("depthSampler", _this._getDepthTexture());
};
this.addEffect(new BABYLON2.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function() {
return _this.motionBlurPostProcess;
}, true));
};
StandardRenderingPipeline2.prototype._getDepthTexture = function() {
if (this._scene.getEngine().getCaps().drawBuffersExtension) {
var renderer = this._scene.enableGeometryBufferRenderer();
return renderer.getGBuffer().textures[0];
}
return this._scene.enableDepthRenderer().getDepthMap();
};
StandardRenderingPipeline2.prototype._disposePostProcesses = function() {
for (var i2 = 0; i2 < this._cameras.length; i2++) {
var camera2 = this._cameras[i2];
if (this.originalPostProcess) {
this.originalPostProcess.dispose(camera2);
}
if (this.downSampleX4PostProcess) {
this.downSampleX4PostProcess.dispose(camera2);
}
if (this.brightPassPostProcess) {
this.brightPassPostProcess.dispose(camera2);
}
if (this.textureAdderPostProcess) {
this.textureAdderPostProcess.dispose(camera2);
}
if (this.textureAdderFinalPostProcess) {
this.textureAdderFinalPostProcess.dispose(camera2);
}
if (this.volumetricLightPostProcess) {
this.volumetricLightPostProcess.dispose(camera2);
}
if (this.volumetricLightSmoothXPostProcess) {
this.volumetricLightSmoothXPostProcess.dispose(camera2);
}
if (this.volumetricLightSmoothYPostProcess) {
this.volumetricLightSmoothYPostProcess.dispose(camera2);
}
if (this.volumetricLightMergePostProces) {
this.volumetricLightMergePostProces.dispose(camera2);
}
if (this.volumetricLightFinalPostProcess) {
this.volumetricLightFinalPostProcess.dispose(camera2);
}
if (this.lensFlarePostProcess) {
this.lensFlarePostProcess.dispose(camera2);
}
if (this.lensFlareComposePostProcess) {
this.lensFlareComposePostProcess.dispose(camera2);
}
for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
this.luminanceDownSamplePostProcesses[j].dispose(camera2);
}
if (this.luminancePostProcess) {
this.luminancePostProcess.dispose(camera2);
}
if (this.hdrPostProcess) {
this.hdrPostProcess.dispose(camera2);
}
if (this.hdrFinalPostProcess) {
this.hdrFinalPostProcess.dispose(camera2);
}
if (this.depthOfFieldPostProcess) {
this.depthOfFieldPostProcess.dispose(camera2);
}
if (this.motionBlurPostProcess) {
this.motionBlurPostProcess.dispose(camera2);
}
if (this.fxaaPostProcess) {
this.fxaaPostProcess.dispose(camera2);
}
for (var j = 0; j < this.blurHPostProcesses.length; j++) {
this.blurHPostProcesses[j].dispose(camera2);
}
for (var j = 0; j < this.blurVPostProcesses.length; j++) {
this.blurVPostProcesses[j].dispose(camera2);
}
}
this.originalPostProcess = null;
this.downSampleX4PostProcess = null;
this.brightPassPostProcess = null;
this.textureAdderPostProcess = null;
this.textureAdderFinalPostProcess = null;
this.volumetricLightPostProcess = null;
this.volumetricLightSmoothXPostProcess = null;
this.volumetricLightSmoothYPostProcess = null;
this.volumetricLightMergePostProces = null;
this.volumetricLightFinalPostProcess = null;
this.lensFlarePostProcess = null;
this.lensFlareComposePostProcess = null;
this.luminancePostProcess = null;
this.hdrPostProcess = null;
this.hdrFinalPostProcess = null;
this.depthOfFieldPostProcess = null;
this.motionBlurPostProcess = null;
this.fxaaPostProcess = null;
this.luminanceDownSamplePostProcesses = [];
this.blurHPostProcesses = [];
this.blurVPostProcesses = [];
};
StandardRenderingPipeline2.prototype.dispose = function() {
this._disposePostProcesses();
this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
_super.prototype.dispose.call(this);
};
StandardRenderingPipeline2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
if (this.sourceLight) {
serializationObject.sourceLightId = this.sourceLight.id;
}
serializationObject.customType = "StandardRenderingPipeline";
return serializationObject;
};
StandardRenderingPipeline2.Parse = function(source, scene, rootUrl) {
var p = BABYLON2.SerializationHelper.Parse(function() {
return new StandardRenderingPipeline2(source._name, scene, source._ratio);
}, source, scene, rootUrl);
if (source.sourceLightId) {
p.sourceLight = scene.getLightByID(source.sourceLightId);
}
return p;
};
StandardRenderingPipeline2.LuminanceSteps = 6;
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "brightThreshold", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "blurWidth", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "horizontalBlur", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "exposure", void 0);
__decorate([
BABYLON2.serializeAsTexture("lensTexture")
], StandardRenderingPipeline2.prototype, "lensTexture", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "volumetricLightCoefficient", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "volumetricLightPower", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "volumetricLightBlurScale", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "hdrMinimumLuminance", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "hdrDecreaseRate", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "hdrIncreaseRate", void 0);
__decorate([
BABYLON2.serializeAsTexture("lensColorTexture")
], StandardRenderingPipeline2.prototype, "lensColorTexture", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "lensFlareStrength", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "lensFlareGhostDispersal", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "lensFlareHaloWidth", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "lensFlareDistortionStrength", void 0);
__decorate([
BABYLON2.serializeAsTexture("lensStarTexture")
], StandardRenderingPipeline2.prototype, "lensStarTexture", void 0);
__decorate([
BABYLON2.serializeAsTexture("lensFlareDirtTexture")
], StandardRenderingPipeline2.prototype, "lensFlareDirtTexture", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "depthOfFieldDistance", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "depthOfFieldBlurWidth", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "motionStrength", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "_ratio", void 0);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "BloomEnabled", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "DepthOfFieldEnabled", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "LensFlareEnabled", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "HDREnabled", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "VLSEnabled", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "MotionBlurEnabled", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "fxaaEnabled", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "volumetricLightStepsCount", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "motionBlurSamples", null);
__decorate([
BABYLON2.serialize()
], StandardRenderingPipeline2.prototype, "samples", null);
return StandardRenderingPipeline2;
}(BABYLON2.PostProcessRenderPipeline)
);
BABYLON2.StandardRenderingPipeline = StandardRenderingPipeline;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FxaaPostProcess = (
/** @class */
function(_super) {
__extends(FxaaPostProcess2, _super);
function FxaaPostProcess2(name, options, camera2, samplingMode, engine, reusable, textureType) {
if (camera2 === void 0) {
camera2 = null;
}
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera2, samplingMode || BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", void 0, true) || this;
var defines = _this._getDefines();
_this.updateEffect(defines);
_this.onApplyObservable.add(function(effect) {
var texelSize = _this.texelSize;
effect.setFloat2("texelSize", texelSize.x, texelSize.y);
});
return _this;
}
FxaaPostProcess2.prototype._getDefines = function() {
var engine = this.getEngine();
if (!engine) {
return null;
}
var glInfo = engine.getGlInfo();
if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
return "#define MALI 1\n";
}
return null;
};
return FxaaPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.FxaaPostProcess = FxaaPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ChromaticAberrationPostProcess = (
/** @class */
function(_super) {
__extends(ChromaticAberrationPostProcess2, _super);
function ChromaticAberrationPostProcess2(name, screenWidth, screenHeight, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera2, samplingMode, engine, reusable, null, textureType, void 0, null, blockCompilation) || this;
_this.aberrationAmount = 30;
_this.radialIntensity = 0;
_this.direction = new BABYLON2.Vector2(0.707, 0.707);
_this.centerPosition = new BABYLON2.Vector2(0.5, 0.5);
_this.onApplyObservable.add(function(effect) {
effect.setFloat("chromatic_aberration", _this.aberrationAmount);
effect.setFloat("screen_width", screenWidth);
effect.setFloat("screen_height", screenHeight);
effect.setFloat("radialIntensity", _this.radialIntensity);
effect.setFloat2("direction", _this.direction.x, _this.direction.y);
effect.setFloat2("centerPosition", _this.centerPosition.x, _this.centerPosition.y);
});
return _this;
}
return ChromaticAberrationPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var GrainPostProcess = (
/** @class */
function(_super) {
__extends(GrainPostProcess2, _super);
function GrainPostProcess2(name, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera2, samplingMode, engine, reusable, null, textureType, void 0, null, blockCompilation) || this;
_this.intensity = 30;
_this.animated = false;
_this.onApplyObservable.add(function(effect) {
effect.setFloat("intensity", _this.intensity);
effect.setFloat("animatedSeed", _this.animated ? Math.random() + 1 : 1);
});
return _this;
}
return GrainPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.GrainPostProcess = GrainPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SharpenPostProcess = (
/** @class */
function(_super) {
__extends(SharpenPostProcess2, _super);
function SharpenPostProcess2(name, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera2, samplingMode, engine, reusable, null, textureType, void 0, null, blockCompilation) || this;
_this.colorAmount = 1;
_this.edgeAmount = 0.3;
_this.onApply = function(effect) {
effect.setFloat2("screenSize", _this.width, _this.height);
effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
};
return _this;
}
return SharpenPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.SharpenPostProcess = SharpenPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BlurPostProcess = (
/** @class */
function(_super) {
__extends(BlurPostProcess2, _super);
function BlurPostProcess2(name, direction, kernel, options, camera2, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.BILINEAR_SAMPLINGMODE;
}
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (defines === void 0) {
defines = "";
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera2, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
_this.direction = direction;
_this.blockCompilation = blockCompilation;
_this._packedFloat = false;
_this._staticDefines = "";
_this._staticDefines = defines;
_this.onApplyObservable.add(function(effect) {
if (_this._outputTexture) {
effect.setFloat2("delta", 1 / _this._outputTexture.width * _this.direction.x, 1 / _this._outputTexture.height * _this.direction.y);
} else {
effect.setFloat2("delta", 1 / _this.width * _this.direction.x, 1 / _this.height * _this.direction.y);
}
});
_this.kernel = kernel;
return _this;
}
Object.defineProperty(BlurPostProcess2.prototype, "kernel", {
/**
* Gets the length in pixels of the blur sample region
*/
get: function() {
return this._idealKernel;
},
/**
* Sets the length in pixels of the blur sample region
*/
set: function(v) {
if (this._idealKernel === v) {
return;
}
v = Math.max(v, 1);
this._idealKernel = v;
this._kernel = this._nearestBestKernel(v);
if (!this.blockCompilation) {
this._updateParameters();
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BlurPostProcess2.prototype, "packedFloat", {
/**
* Gets wether or not the blur is unpacking/repacking floats
*/
get: function() {
return this._packedFloat;
},
/**
* Sets wether or not the blur needs to unpack/repack floats
*/
set: function(v) {
if (this._packedFloat === v) {
return;
}
this._packedFloat = v;
if (!this.blockCompilation) {
this._updateParameters();
}
},
enumerable: true,
configurable: true
});
BlurPostProcess2.prototype.updateEffect = function(defines, uniforms, samplers, indexParameters, onCompiled, onError) {
if (defines === void 0) {
defines = null;
}
if (uniforms === void 0) {
uniforms = null;
}
if (samplers === void 0) {
samplers = null;
}
this._updateParameters(onCompiled, onError);
};
BlurPostProcess2.prototype._updateParameters = function(onCompiled, onError) {
var N = this._kernel;
var centerIndex = (N - 1) / 2;
var offsets = [];
var weights = [];
var totalWeight = 0;
for (var i2 = 0; i2 < N; i2++) {
var u = i2 / (N - 1);
var w = this._gaussianWeight(u * 2 - 1);
offsets[i2] = i2 - centerIndex;
weights[i2] = w;
totalWeight += w;
}
for (var i2 = 0; i2 < weights.length; i2++) {
weights[i2] /= totalWeight;
}
var linearSamplingWeights = [];
var linearSamplingOffsets = [];
var linearSamplingMap = [];
for (var i2 = 0; i2 <= centerIndex; i2 += 2) {
var j = Math.min(i2 + 1, Math.floor(centerIndex));
var singleCenterSample = i2 === j;
if (singleCenterSample) {
linearSamplingMap.push({ o: offsets[i2], w: weights[i2] });
} else {
var sharedCell = j === centerIndex;
var weightLinear = weights[i2] + weights[j] * (sharedCell ? 0.5 : 1);
var offsetLinear = offsets[i2] + 1 / (1 + weights[i2] / weights[j]);
if (offsetLinear === 0) {
linearSamplingMap.push({ o: offsets[i2], w: weights[i2] });
linearSamplingMap.push({ o: offsets[i2 + 1], w: weights[i2 + 1] });
} else {
linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
}
}
}
for (var i2 = 0; i2 < linearSamplingMap.length; i2++) {
linearSamplingOffsets[i2] = linearSamplingMap[i2].o;
linearSamplingWeights[i2] = linearSamplingMap[i2].w;
}
offsets = linearSamplingOffsets;
weights = linearSamplingWeights;
var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
var freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1;
var varyingCount = Math.min(offsets.length, freeVaryingVec2);
var defines = "";
defines += this._staticDefines;
if (this._staticDefines.indexOf("DOF") != -1) {
defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
varyingCount--;
}
for (var i2 = 0; i2 < varyingCount; i2++) {
defines += "#define KERNEL_OFFSET" + i2 + " " + this._glslFloat(offsets[i2]) + "\r\n";
defines += "#define KERNEL_WEIGHT" + i2 + " " + this._glslFloat(weights[i2]) + "\r\n";
}
var depCount = 0;
for (var i2 = freeVaryingVec2; i2 < offsets.length; i2++) {
defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i2]) + "\r\n";
defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i2]) + "\r\n";
depCount++;
}
if (this.packedFloat) {
defines += "#define PACKEDFLOAT 1";
}
this.blockCompilation = false;
_super.prototype.updateEffect.call(this, defines, null, null, {
varyingCount,
depCount
}, onCompiled, onError);
};
BlurPostProcess2.prototype._nearestBestKernel = function(idealKernel) {
var v = Math.round(idealKernel);
for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
var k = _a[_i];
if (k % 2 !== 0 && Math.floor(k / 2) % 2 === 0 && k > 0) {
return Math.max(k, 3);
}
}
return Math.max(v, 3);
};
BlurPostProcess2.prototype._gaussianWeight = function(x) {
var sigma = 1 / 3;
var denominator = Math.sqrt(2 * Math.PI) * sigma;
var exponent = -(x * x / (2 * sigma * sigma));
var weight = 1 / denominator * Math.exp(exponent);
return weight;
};
BlurPostProcess2.prototype._glslFloat = function(x, decimalFigures) {
if (decimalFigures === void 0) {
decimalFigures = 8;
}
return x.toFixed(decimalFigures).replace(/0+$/, "");
};
return BlurPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.BlurPostProcess = BlurPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DepthOfFieldBlurPostProcess = (
/** @class */
function(_super) {
__extends(DepthOfFieldBlurPostProcess2, _super);
function DepthOfFieldBlurPostProcess2(name, scene, direction, kernel, options, camera2, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
if (imageToBlur === void 0) {
imageToBlur = null;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.BILINEAR_SAMPLINGMODE;
}
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, direction, kernel, options, camera2, samplingMode = BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
_this.direction = direction;
_this.onApplyObservable.add(function(effect) {
if (imageToBlur != null) {
effect.setTextureFromPostProcess("textureSampler", imageToBlur);
}
effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
if (scene.activeCamera) {
effect.setFloat2("cameraMinMaxZ", scene.activeCamera.minZ, scene.activeCamera.maxZ);
}
});
return _this;
}
return DepthOfFieldBlurPostProcess2;
}(BABYLON2.BlurPostProcess)
);
BABYLON2.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DepthOfFieldMergePostProcessOptions = (
/** @class */
function() {
function DepthOfFieldMergePostProcessOptions2() {
}
return DepthOfFieldMergePostProcessOptions2;
}()
);
BABYLON2.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
var DepthOfFieldMergePostProcess = (
/** @class */
function(_super) {
__extends(DepthOfFieldMergePostProcess2, _super);
function DepthOfFieldMergePostProcess2(name, originalFromInput, circleOfConfusion, blurSteps, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera2, samplingMode, engine, reusable, null, textureType, void 0, null, true) || this;
_this.blurSteps = blurSteps;
_this.onApplyObservable.add(function(effect) {
effect.setTextureFromPostProcess("textureSampler", originalFromInput);
effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
blurSteps.forEach(function(step, index) {
effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
});
});
if (!blockCompilation) {
_this.updateEffect();
}
return _this;
}
DepthOfFieldMergePostProcess2.prototype.updateEffect = function(defines, uniforms, samplers, indexParameters, onCompiled, onError) {
if (defines === void 0) {
defines = null;
}
if (uniforms === void 0) {
uniforms = null;
}
if (samplers === void 0) {
samplers = null;
}
if (!defines) {
defines = "";
defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
}
_super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
};
return DepthOfFieldMergePostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var CircleOfConfusionPostProcess = (
/** @class */
function(_super) {
__extends(CircleOfConfusionPostProcess2, _super);
function CircleOfConfusionPostProcess2(name, depthTexture, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera2, samplingMode, engine, reusable, null, textureType, void 0, null, blockCompilation) || this;
_this.lensSize = 50;
_this.fStop = 1.4;
_this.focusDistance = 2e3;
_this.focalLength = 50;
_this._depthTexture = null;
_this._depthTexture = depthTexture;
_this.onApplyObservable.add(function(effect) {
if (!_this._depthTexture) {
BABYLON2.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
return;
}
effect.setTexture("depthSampler", _this._depthTexture);
var aperture = _this.lensSize / _this.fStop;
var cocPrecalculation = aperture * _this.focalLength / (_this.focusDistance - _this.focalLength);
effect.setFloat("focusDistance", _this.focusDistance);
effect.setFloat("cocPrecalculation", cocPrecalculation);
effect.setFloat2("cameraMinMaxZ", _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
});
return _this;
}
Object.defineProperty(CircleOfConfusionPostProcess2.prototype, "depthTexture", {
/**
* Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
*/
set: function(value) {
this._depthTexture = value;
},
enumerable: true,
configurable: true
});
return CircleOfConfusionPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DepthOfFieldEffectBlurLevel;
(function(DepthOfFieldEffectBlurLevel2) {
DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["Low"] = 0] = "Low";
DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["Medium"] = 1] = "Medium";
DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["High"] = 2] = "High";
})(DepthOfFieldEffectBlurLevel = BABYLON2.DepthOfFieldEffectBlurLevel || (BABYLON2.DepthOfFieldEffectBlurLevel = {}));
var DepthOfFieldEffect = (
/** @class */
function(_super) {
__extends(DepthOfFieldEffect2, _super);
function DepthOfFieldEffect2(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
if (blurLevel === void 0) {
blurLevel = DepthOfFieldEffectBlurLevel.Low;
}
if (pipelineTextureType === void 0) {
pipelineTextureType = 0;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, scene.getEngine(), "depth of field", function() {
return _this._effects;
}, true) || this;
_this._effects = [];
_this._circleOfConfusion = new BABYLON2.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
_this._depthOfFieldBlurY = [];
_this._depthOfFieldBlurX = [];
var blurCount = 1;
var kernelSize = 15;
switch (blurLevel) {
case DepthOfFieldEffectBlurLevel.High: {
blurCount = 3;
kernelSize = 51;
break;
}
case DepthOfFieldEffectBlurLevel.Medium: {
blurCount = 2;
kernelSize = 31;
break;
}
default: {
kernelSize = 15;
blurCount = 1;
break;
}
}
var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
var ratio = 1;
for (var i2 = 0; i2 < blurCount; i2++) {
var blurY = new BABYLON2.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON2.Vector2(0, 1), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i2 == 0 ? _this._circleOfConfusion : null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
blurY.autoClear = false;
ratio = 0.75 / Math.pow(2, i2);
var blurX = new BABYLON2.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON2.Vector2(1, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
blurX.autoClear = false;
_this._depthOfFieldBlurY.push(blurY);
_this._depthOfFieldBlurX.push(blurX);
}
_this._effects = [_this._circleOfConfusion];
for (var i2 = 0; i2 < _this._depthOfFieldBlurX.length; i2++) {
_this._effects.push(_this._depthOfFieldBlurY[i2]);
_this._effects.push(_this._depthOfFieldBlurX[i2]);
}
_this._dofMerge = new BABYLON2.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
_this._dofMerge.autoClear = false;
_this._effects.push(_this._dofMerge);
return _this;
}
Object.defineProperty(DepthOfFieldEffect2.prototype, "focalLength", {
get: function() {
return this._circleOfConfusion.focalLength;
},
/**
* The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
*/
set: function(value) {
this._circleOfConfusion.focalLength = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DepthOfFieldEffect2.prototype, "fStop", {
get: function() {
return this._circleOfConfusion.fStop;
},
/**
* F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
*/
set: function(value) {
this._circleOfConfusion.fStop = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DepthOfFieldEffect2.prototype, "focusDistance", {
get: function() {
return this._circleOfConfusion.focusDistance;
},
/**
* Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
*/
set: function(value) {
this._circleOfConfusion.focusDistance = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DepthOfFieldEffect2.prototype, "lensSize", {
get: function() {
return this._circleOfConfusion.lensSize;
},
/**
* Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
*/
set: function(value) {
this._circleOfConfusion.lensSize = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DepthOfFieldEffect2.prototype, "depthTexture", {
/**
* Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
*/
set: function(value) {
this._circleOfConfusion.depthTexture = value;
},
enumerable: true,
configurable: true
});
DepthOfFieldEffect2.prototype.disposeEffects = function(camera2) {
for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
this._effects[effectIndex].dispose(camera2);
}
};
DepthOfFieldEffect2.prototype._updateEffects = function() {
for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
this._effects[effectIndex].updateEffect();
}
};
DepthOfFieldEffect2.prototype._isReady = function() {
for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
if (!this._effects[effectIndex].isReady()) {
return false;
}
}
return true;
};
return DepthOfFieldEffect2;
}(BABYLON2.PostProcessRenderEffect)
);
BABYLON2.DepthOfFieldEffect = DepthOfFieldEffect;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BloomMergePostProcess = (
/** @class */
function(_super) {
__extends(BloomMergePostProcess2, _super);
function BloomMergePostProcess2(name, originalFromInput, blurred, weight, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera2, samplingMode, engine, reusable, null, textureType, void 0, null, true) || this;
_this.weight = weight;
_this.onApplyObservable.add(function(effect) {
effect.setTextureFromPostProcess("textureSampler", originalFromInput);
effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
effect.setFloat("bloomWeight", _this.weight);
});
if (!blockCompilation) {
_this.updateEffect();
}
return _this;
}
return BloomMergePostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.BloomMergePostProcess = BloomMergePostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ExtractHighlightsPostProcess = (
/** @class */
function(_super) {
__extends(ExtractHighlightsPostProcess2, _super);
function ExtractHighlightsPostProcess2(name, options, camera2, samplingMode, engine, reusable, textureType, blockCompilation) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera2, samplingMode, engine, reusable, null, textureType, void 0, null, blockCompilation) || this;
_this.threshold = 0.9;
_this._exposure = 1;
_this._inputPostProcess = null;
_this.onApplyObservable.add(function(effect) {
if (_this._inputPostProcess) {
effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
}
effect.setFloat("threshold", Math.pow(_this.threshold, BABYLON2.ToGammaSpace));
effect.setFloat("exposure", _this._exposure);
});
return _this;
}
return ExtractHighlightsPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BloomEffect = (
/** @class */
function(_super) {
__extends(BloomEffect2, _super);
function BloomEffect2(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
if (pipelineTextureType === void 0) {
pipelineTextureType = 0;
}
if (blockCompilation === void 0) {
blockCompilation = false;
}
var _this = _super.call(this, scene.getEngine(), "bloom", function() {
return _this._effects;
}, true) || this;
_this.bloomScale = bloomScale;
_this._effects = [];
_this._downscale = new BABYLON2.ExtractHighlightsPostProcess("highlights", 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
_this._blurX = new BABYLON2.BlurPostProcess("horizontal blur", new BABYLON2.Vector2(1, 0), 10, bloomScale, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, void 0, blockCompilation);
_this._blurX.alwaysForcePOT = true;
_this._blurX.autoClear = false;
_this._blurY = new BABYLON2.BlurPostProcess("vertical blur", new BABYLON2.Vector2(0, 1), 10, bloomScale, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, void 0, blockCompilation);
_this._blurY.alwaysForcePOT = true;
_this._blurY.autoClear = false;
_this.kernel = bloomKernel;
_this._effects = [_this._downscale, _this._blurX, _this._blurY];
_this._merge = new BABYLON2.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
_this._merge.autoClear = false;
_this._effects.push(_this._merge);
return _this;
}
Object.defineProperty(BloomEffect2.prototype, "threshold", {
/**
* The luminance threshold to find bright areas of the image to bloom.
*/
get: function() {
return this._downscale.threshold;
},
set: function(value) {
this._downscale.threshold = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BloomEffect2.prototype, "weight", {
/**
* The strength of the bloom.
*/
get: function() {
return this._merge.weight;
},
set: function(value) {
this._merge.weight = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BloomEffect2.prototype, "kernel", {
/**
* Specifies the size of the bloom blur kernel, relative to the final output size
*/
get: function() {
return this._blurX.kernel / this.bloomScale;
},
set: function(value) {
this._blurX.kernel = value * this.bloomScale;
this._blurY.kernel = value * this.bloomScale;
},
enumerable: true,
configurable: true
});
BloomEffect2.prototype.disposeEffects = function(camera2) {
for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
this._effects[effectIndex].dispose(camera2);
}
};
BloomEffect2.prototype._updateEffects = function() {
for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
this._effects[effectIndex].updateEffect();
}
};
BloomEffect2.prototype._isReady = function() {
for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
if (!this._effects[effectIndex].isReady()) {
return false;
}
}
return true;
};
return BloomEffect2;
}(BABYLON2.PostProcessRenderEffect)
);
BABYLON2.BloomEffect = BloomEffect;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DefaultRenderingPipeline = (
/** @class */
function(_super) {
__extends(DefaultRenderingPipeline2, _super);
function DefaultRenderingPipeline2(name, hdr, scene, cameras, automaticBuild) {
if (name === void 0) {
name = "";
}
if (hdr === void 0) {
hdr = true;
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
if (automaticBuild === void 0) {
automaticBuild = true;
}
var _this = _super.call(this, scene.getEngine(), name) || this;
_this._camerasToBeAttached = [];
_this.SharpenPostProcessId = "SharpenPostProcessEffect";
_this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
_this.FxaaPostProcessId = "FxaaPostProcessEffect";
_this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
_this.GrainPostProcessId = "GrainPostProcessEffect";
_this._glowLayer = null;
_this.animations = [];
_this._imageProcessingConfigurationObserver = null;
_this._sharpenEnabled = false;
_this._bloomEnabled = false;
_this._depthOfFieldEnabled = false;
_this._depthOfFieldBlurLevel = BABYLON2.DepthOfFieldEffectBlurLevel.Low;
_this._fxaaEnabled = false;
_this._imageProcessingEnabled = true;
_this._bloomScale = 0.5;
_this._chromaticAberrationEnabled = false;
_this._grainEnabled = false;
_this._buildAllowed = true;
_this._resizeObserver = null;
_this._hardwareScaleLevel = 1;
_this._bloomKernel = 64;
_this._bloomWeight = 0.15;
_this._bloomThreshold = 0.9;
_this._samples = 1;
_this._hasCleared = false;
_this._prevPostProcess = null;
_this._prevPrevPostProcess = null;
_this._depthOfFieldSceneObserver = null;
_this._cameras = cameras || scene.cameras;
_this._cameras = _this._cameras.slice();
_this._camerasToBeAttached = _this._cameras.slice();
_this._buildAllowed = automaticBuild;
_this._scene = scene;
var caps = _this._scene.getEngine().getCaps();
_this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
if (_this._hdr) {
if (caps.textureHalfFloatRender) {
_this._defaultPipelineTextureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
} else if (caps.textureFloatRender) {
_this._defaultPipelineTextureType = BABYLON2.Engine.TEXTURETYPE_FLOAT;
}
} else {
_this._defaultPipelineTextureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
scene.postProcessRenderPipelineManager.addPipeline(_this);
var engine = _this._scene.getEngine();
_this.sharpen = new BABYLON2.SharpenPostProcess("sharpen", 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
_this._sharpenEffect = new BABYLON2.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function() {
return _this.sharpen;
}, true);
_this.depthOfField = new BABYLON2.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
_this.bloom = new BABYLON2.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
_this.chromaticAberration = new BABYLON2.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
_this._chromaticAberrationEffect = new BABYLON2.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function() {
return _this.chromaticAberration;
}, true);
_this.grain = new BABYLON2.GrainPostProcess("Grain", 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
_this._grainEffect = new BABYLON2.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function() {
return _this.grain;
}, true);
_this._resizeObserver = engine.onResizeObservable.add(function() {
_this._hardwareScaleLevel = engine.getHardwareScalingLevel();
_this.bloomKernel = _this.bloomKernel;
});
_this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function() {
_this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
});
_this._buildPipeline();
return _this;
}
Object.defineProperty(DefaultRenderingPipeline2.prototype, "sharpenEnabled", {
get: function() {
return this._sharpenEnabled;
},
/**
* Enable or disable the sharpen process from the pipeline
*/
set: function(enabled) {
if (this._sharpenEnabled === enabled) {
return;
}
this._sharpenEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "bloomKernel", {
/**
* Specifies the size of the bloom blur kernel, relative to the final output size
*/
get: function() {
return this._bloomKernel;
},
set: function(value) {
this._bloomKernel = value;
this.bloom.kernel = value / this._hardwareScaleLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "bloomWeight", {
get: function() {
return this._bloomWeight;
},
/**
* The strength of the bloom.
*/
set: function(value) {
if (this._bloomWeight === value) {
return;
}
this.bloom.weight = value;
this._bloomWeight = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "bloomThreshold", {
get: function() {
return this._bloomThreshold;
},
/**
* The strength of the bloom.
*/
set: function(value) {
if (this._bloomThreshold === value) {
return;
}
this.bloom.threshold = value;
this._bloomThreshold = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "bloomScale", {
get: function() {
return this._bloomScale;
},
/**
* The scale of the bloom, lower value will provide better performance.
*/
set: function(value) {
if (this._bloomScale === value) {
return;
}
this._bloomScale = value;
this._rebuildBloom();
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "bloomEnabled", {
get: function() {
return this._bloomEnabled;
},
/**
* Enable or disable the bloom from the pipeline
*/
set: function(enabled) {
if (this._bloomEnabled === enabled) {
return;
}
this._bloomEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
DefaultRenderingPipeline2.prototype._rebuildBloom = function() {
var oldBloom = this.bloom;
this.bloom = new BABYLON2.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
this.bloom.threshold = oldBloom.threshold;
for (var i2 = 0; i2 < this._cameras.length; i2++) {
oldBloom.disposeEffects(this._cameras[i2]);
}
};
Object.defineProperty(DefaultRenderingPipeline2.prototype, "depthOfFieldEnabled", {
/**
* If the depth of field is enabled.
*/
get: function() {
return this._depthOfFieldEnabled;
},
set: function(enabled) {
if (this._depthOfFieldEnabled === enabled) {
return;
}
this._depthOfFieldEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "depthOfFieldBlurLevel", {
/**
* Blur level of the depth of field effect. (Higher blur will effect performance)
*/
get: function() {
return this._depthOfFieldBlurLevel;
},
set: function(value) {
if (this._depthOfFieldBlurLevel === value) {
return;
}
this._depthOfFieldBlurLevel = value;
var oldDof = this.depthOfField;
this.depthOfField = new BABYLON2.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
this.depthOfField.focalLength = oldDof.focalLength;
this.depthOfField.focusDistance = oldDof.focusDistance;
this.depthOfField.fStop = oldDof.fStop;
this.depthOfField.lensSize = oldDof.lensSize;
for (var i2 = 0; i2 < this._cameras.length; i2++) {
oldDof.disposeEffects(this._cameras[i2]);
}
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "fxaaEnabled", {
get: function() {
return this._fxaaEnabled;
},
/**
* If the anti aliasing is enabled.
*/
set: function(enabled) {
if (this._fxaaEnabled === enabled) {
return;
}
this._fxaaEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "samples", {
get: function() {
return this._samples;
},
/**
* MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
*/
set: function(sampleCount) {
if (this._samples === sampleCount) {
return;
}
this._samples = sampleCount;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "imageProcessingEnabled", {
get: function() {
return this._imageProcessingEnabled;
},
/**
* If image processing is enabled.
*/
set: function(enabled) {
if (this._imageProcessingEnabled === enabled) {
return;
}
this._imageProcessingEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "glowLayerEnabled", {
get: function() {
return this._glowLayer == null;
},
/**
* If glow layer is enabled. (Adds a glow effect to emmissive materials)
*/
set: function(enabled) {
if (enabled && !this._glowLayer) {
this._glowLayer = new BABYLON2.GlowLayer("", this._scene);
} else if (!enabled && this._glowLayer) {
this._glowLayer.dispose();
this._glowLayer = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "chromaticAberrationEnabled", {
get: function() {
return this._chromaticAberrationEnabled;
},
/**
* Enable or disable the chromaticAberration process from the pipeline
*/
set: function(enabled) {
if (this._chromaticAberrationEnabled === enabled) {
return;
}
this._chromaticAberrationEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
Object.defineProperty(DefaultRenderingPipeline2.prototype, "grainEnabled", {
get: function() {
return this._grainEnabled;
},
/**
* Enable or disable the grain process from the pipeline
*/
set: function(enabled) {
if (this._grainEnabled === enabled) {
return;
}
this._grainEnabled = enabled;
this._buildPipeline();
},
enumerable: true,
configurable: true
});
DefaultRenderingPipeline2.prototype.prepare = function() {
var previousState = this._buildAllowed;
this._buildAllowed = true;
this._buildPipeline();
this._buildAllowed = previousState;
};
DefaultRenderingPipeline2.prototype._setAutoClearAndTextureSharing = function(postProcess, skipTextureSharing) {
if (skipTextureSharing === void 0) {
skipTextureSharing = false;
}
if (this._hasCleared) {
postProcess.autoClear = false;
} else {
postProcess.autoClear = true;
this._scene.autoClear = false;
this._hasCleared = true;
}
if (!skipTextureSharing) {
if (this._prevPrevPostProcess) {
postProcess.shareOutputWith(this._prevPrevPostProcess);
} else {
postProcess.useOwnOutput();
}
if (this._prevPostProcess) {
this._prevPrevPostProcess = this._prevPostProcess;
}
this._prevPostProcess = postProcess;
}
};
DefaultRenderingPipeline2.prototype._buildPipeline = function() {
var _this = this;
if (!this._buildAllowed) {
return;
}
this._scene.autoClear = true;
var engine = this._scene.getEngine();
this._disposePostProcesses();
if (this._cameras !== null) {
this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
this._cameras = this._camerasToBeAttached.slice();
}
this._reset();
this._prevPostProcess = null;
this._prevPrevPostProcess = null;
this._hasCleared = false;
if (this.depthOfFieldEnabled) {
if (this._cameras.length > 1) {
for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
var camera2 = _a[_i];
var depthRenderer = this._scene.enableDepthRenderer(camera2);
depthRenderer.useOnlyInActiveCamera = true;
}
this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function(scene) {
if (_this._cameras.indexOf(scene.activeCamera) > -1) {
_this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
}
});
} else {
this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
this.depthOfField.depthTexture = depthRenderer.getDepthMap();
}
if (!this.depthOfField._isReady()) {
this.depthOfField._updateEffects();
}
this.addEffect(this.depthOfField);
this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
} else {
this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
}
if (this.bloomEnabled) {
if (!this.bloom._isReady()) {
this.bloom._updateEffects();
}
this.addEffect(this.bloom);
this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
}
if (this._imageProcessingEnabled) {
this.imageProcessing = new BABYLON2.ImageProcessingPostProcess("imageProcessing", 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
if (this._hdr) {
this.addEffect(new BABYLON2.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function() {
return _this.imageProcessing;
}, true));
this._setAutoClearAndTextureSharing(this.imageProcessing);
} else {
this._scene.imageProcessingConfiguration.applyByPostProcess = false;
}
}
if (this.sharpenEnabled) {
if (!this.sharpen.isReady()) {
this.sharpen.updateEffect();
}
this.addEffect(this._sharpenEffect);
this._setAutoClearAndTextureSharing(this.sharpen);
}
if (this.grainEnabled) {
if (!this.grain.isReady()) {
this.grain.updateEffect();
}
this.addEffect(this._grainEffect);
this._setAutoClearAndTextureSharing(this.grain);
}
if (this.chromaticAberrationEnabled) {
if (!this.chromaticAberration.isReady()) {
this.chromaticAberration.updateEffect();
}
this.addEffect(this._chromaticAberrationEffect);
this._setAutoClearAndTextureSharing(this.chromaticAberration);
}
if (this.fxaaEnabled) {
this.fxaa = new BABYLON2.FxaaPostProcess("fxaa", 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
this.addEffect(new BABYLON2.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function() {
return _this.fxaa;
}, true));
this._setAutoClearAndTextureSharing(this.fxaa, true);
}
if (this._cameras !== null) {
this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
}
if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
BABYLON2.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
}
};
DefaultRenderingPipeline2.prototype._disposePostProcesses = function(disposeNonRecreated) {
if (disposeNonRecreated === void 0) {
disposeNonRecreated = false;
}
for (var i2 = 0; i2 < this._cameras.length; i2++) {
var camera2 = this._cameras[i2];
if (this.imageProcessing) {
this.imageProcessing.dispose(camera2);
}
if (this.fxaa) {
this.fxaa.dispose(camera2);
}
if (disposeNonRecreated) {
if (this.sharpen) {
this.sharpen.dispose(camera2);
}
if (this.depthOfField) {
this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
this.depthOfField.disposeEffects(camera2);
}
if (this.bloom) {
this.bloom.disposeEffects(camera2);
}
if (this.chromaticAberration) {
this.chromaticAberration.dispose(camera2);
}
if (this.grain) {
this.grain.dispose(camera2);
}
if (this._glowLayer) {
this._glowLayer.dispose();
}
}
}
this.imageProcessing = null;
this.fxaa = null;
if (disposeNonRecreated) {
this.sharpen = null;
this._sharpenEffect = null;
this.depthOfField = null;
this.bloom = null;
this.chromaticAberration = null;
this._chromaticAberrationEffect = null;
this.grain = null;
this._grainEffect = null;
this._glowLayer = null;
}
};
DefaultRenderingPipeline2.prototype.addCamera = function(camera2) {
this._camerasToBeAttached.push(camera2);
this._buildPipeline();
};
DefaultRenderingPipeline2.prototype.removeCamera = function(camera2) {
var index = this._camerasToBeAttached.indexOf(camera2);
this._camerasToBeAttached.splice(index, 1);
this._buildPipeline();
};
DefaultRenderingPipeline2.prototype.dispose = function() {
this._disposePostProcesses(true);
this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
this._scene.autoClear = true;
if (this._resizeObserver) {
this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
this._resizeObserver = null;
}
this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
_super.prototype.dispose.call(this);
};
DefaultRenderingPipeline2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "DefaultRenderingPipeline";
return serializationObject;
};
DefaultRenderingPipeline2.Parse = function(source, scene, rootUrl) {
return BABYLON2.SerializationHelper.Parse(function() {
return new DefaultRenderingPipeline2(source._name, source._name._hdr, scene);
}, source, scene, rootUrl);
};
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "sharpenEnabled", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "bloomKernel", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "_bloomWeight", void 0);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "_bloomThreshold", void 0);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "_hdr", void 0);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "bloomWeight", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "bloomThreshold", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "bloomScale", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "bloomEnabled", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "depthOfFieldEnabled", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "depthOfFieldBlurLevel", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "fxaaEnabled", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "samples", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "imageProcessingEnabled", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "glowLayerEnabled", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "chromaticAberrationEnabled", null);
__decorate([
BABYLON2.serialize()
], DefaultRenderingPipeline2.prototype, "grainEnabled", null);
return DefaultRenderingPipeline2;
}(BABYLON2.PostProcessRenderPipeline)
);
BABYLON2.DefaultRenderingPipeline = DefaultRenderingPipeline;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ImageProcessingConfigurationDefines = (
/** @class */
function(_super) {
__extends(ImageProcessingConfigurationDefines2, _super);
function ImageProcessingConfigurationDefines2() {
var _this = _super.call(this) || this;
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.TONEMAPPING_ACES = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.EXPOSURE = false;
_this.rebuild();
return _this;
}
return ImageProcessingConfigurationDefines2;
}(BABYLON2.MaterialDefines)
);
BABYLON2.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
var ImageProcessingConfiguration = (
/** @class */
function() {
function ImageProcessingConfiguration2() {
this.colorCurves = new BABYLON2.ColorCurves();
this._colorCurvesEnabled = false;
this._colorGradingEnabled = false;
this._colorGradingWithGreenDepth = true;
this._colorGradingBGR = true;
this._exposure = 1;
this._toneMappingEnabled = false;
this._toneMappingType = ImageProcessingConfiguration2.TONEMAPPING_STANDARD;
this._contrast = 1;
this.vignetteStretch = 0;
this.vignetteCentreX = 0;
this.vignetteCentreY = 0;
this.vignetteWeight = 1.5;
this.vignetteColor = new BABYLON2.Color4(0, 0, 0, 0);
this.vignetteCameraFov = 0.5;
this._vignetteBlendMode = ImageProcessingConfiguration2.VIGNETTEMODE_MULTIPLY;
this._vignetteEnabled = false;
this._applyByPostProcess = false;
this._isEnabled = true;
this.onUpdateParameters = new BABYLON2.Observable();
}
Object.defineProperty(ImageProcessingConfiguration2.prototype, "colorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function() {
return this._colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function(value) {
if (this._colorCurvesEnabled === value) {
return;
}
this._colorCurvesEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "colorGradingTexture", {
/**
* Color grading LUT texture used in the effect if colorGradingEnabled is set to true
*/
get: function() {
return this._colorGradingTexture;
},
/**
* Color grading LUT texture used in the effect if colorGradingEnabled is set to true
*/
set: function(value) {
if (this._colorGradingTexture === value) {
return;
}
this._colorGradingTexture = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "colorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function() {
return this._colorGradingEnabled;
},
/**
* Sets wether the color grading effect is enabled.
*/
set: function(value) {
if (this._colorGradingEnabled === value) {
return;
}
this._colorGradingEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "colorGradingWithGreenDepth", {
/**
* Gets wether the color grading effect is using a green depth for the 3d Texture.
*/
get: function() {
return this._colorGradingWithGreenDepth;
},
/**
* Sets wether the color grading effect is using a green depth for the 3d Texture.
*/
set: function(value) {
if (this._colorGradingWithGreenDepth === value) {
return;
}
this._colorGradingWithGreenDepth = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "colorGradingBGR", {
/**
* Gets wether the color grading texture contains BGR values.
*/
get: function() {
return this._colorGradingBGR;
},
/**
* Sets wether the color grading texture contains BGR values.
*/
set: function(value) {
if (this._colorGradingBGR === value) {
return;
}
this._colorGradingBGR = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "exposure", {
/**
* Gets the Exposure used in the effect.
*/
get: function() {
return this._exposure;
},
/**
* Sets the Exposure used in the effect.
*/
set: function(value) {
if (this._exposure === value) {
return;
}
this._exposure = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "toneMappingEnabled", {
/**
* Gets wether the tone mapping effect is enabled.
*/
get: function() {
return this._toneMappingEnabled;
},
/**
* Sets wether the tone mapping effect is enabled.
*/
set: function(value) {
if (this._toneMappingEnabled === value) {
return;
}
this._toneMappingEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "toneMappingType", {
/**
* Gets the type of tone mapping effect.
*/
get: function() {
return this._toneMappingType;
},
/**
* Sets the type of tone mapping effect used in BabylonJS.
*/
set: function(value) {
if (this._toneMappingType === value) {
return;
}
this._toneMappingType = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "contrast", {
/**
* Gets the contrast used in the effect.
*/
get: function() {
return this._contrast;
},
/**
* Sets the contrast used in the effect.
*/
set: function(value) {
if (this._contrast === value) {
return;
}
this._contrast = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "vignetteBlendMode", {
/**
* Gets the vignette blend mode allowing different kind of effect.
*/
get: function() {
return this._vignetteBlendMode;
},
/**
* Sets the vignette blend mode allowing different kind of effect.
*/
set: function(value) {
if (this._vignetteBlendMode === value) {
return;
}
this._vignetteBlendMode = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "vignetteEnabled", {
/**
* Gets wether the vignette effect is enabled.
*/
get: function() {
return this._vignetteEnabled;
},
/**
* Sets wether the vignette effect is enabled.
*/
set: function(value) {
if (this._vignetteEnabled === value) {
return;
}
this._vignetteEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "applyByPostProcess", {
/**
* Gets wether the image processing is applied through a post process or not.
*/
get: function() {
return this._applyByPostProcess;
},
/**
* Sets wether the image processing is applied through a post process or not.
*/
set: function(value) {
if (this._applyByPostProcess === value) {
return;
}
this._applyByPostProcess = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2.prototype, "isEnabled", {
/**
* Gets wether the image processing is enabled or not.
*/
get: function() {
return this._isEnabled;
},
/**
* Sets wether the image processing is enabled or not.
*/
set: function(value) {
if (this._isEnabled === value) {
return;
}
this._isEnabled = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
ImageProcessingConfiguration2.prototype._updateParameters = function() {
this.onUpdateParameters.notifyObservers(this);
};
ImageProcessingConfiguration2.prototype.getClassName = function() {
return "ImageProcessingConfiguration";
};
ImageProcessingConfiguration2.PrepareUniforms = function(uniforms, defines) {
if (defines.EXPOSURE) {
uniforms.push("exposureLinear");
}
if (defines.CONTRAST) {
uniforms.push("contrast");
}
if (defines.COLORGRADING) {
uniforms.push("colorTransformSettings");
}
if (defines.VIGNETTE) {
uniforms.push("vInverseScreenSize");
uniforms.push("vignetteSettings1");
uniforms.push("vignetteSettings2");
}
if (defines.COLORCURVES) {
BABYLON2.ColorCurves.PrepareUniforms(uniforms);
}
};
ImageProcessingConfiguration2.PrepareSamplers = function(samplersList, defines) {
if (defines.COLORGRADING) {
samplersList.push("txColorTransform");
}
};
ImageProcessingConfiguration2.prototype.prepareDefines = function(defines, forPostProcess) {
if (forPostProcess === void 0) {
forPostProcess = false;
}
if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
defines.VIGNETTE = false;
defines.TONEMAPPING = false;
defines.TONEMAPPING_ACES = false;
defines.CONTRAST = false;
defines.EXPOSURE = false;
defines.COLORCURVES = false;
defines.COLORGRADING = false;
defines.COLORGRADING3D = false;
defines.IMAGEPROCESSING = false;
defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
return;
}
defines.VIGNETTE = this.vignetteEnabled;
defines.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === ImageProcessingConfiguration2._VIGNETTEMODE_MULTIPLY;
defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
defines.TONEMAPPING = this.toneMappingEnabled;
switch (this._toneMappingType) {
case ImageProcessingConfiguration2.TONEMAPPING_ACES:
defines.TONEMAPPING_ACES = true;
break;
}
defines.CONTRAST = this.contrast !== 1;
defines.EXPOSURE = this.exposure !== 1;
defines.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves;
defines.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture;
if (defines.COLORGRADING) {
defines.COLORGRADING3D = this.colorGradingTexture.is3D;
} else {
defines.COLORGRADING3D = false;
}
defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
};
ImageProcessingConfiguration2.prototype.isReady = function() {
return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
};
ImageProcessingConfiguration2.prototype.bind = function(effect, aspectRatio) {
if (aspectRatio === void 0) {
aspectRatio = 1;
}
if (this._colorCurvesEnabled && this.colorCurves) {
BABYLON2.ColorCurves.Bind(this.colorCurves, effect);
}
if (this._vignetteEnabled) {
var inverseWidth = 1 / effect.getEngine().getRenderWidth();
var inverseHeight = 1 / effect.getEngine().getRenderHeight();
effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
var vignetteScaleX = vignetteScaleY * aspectRatio;
var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
vignetteScaleX = BABYLON2.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
vignetteScaleY = BABYLON2.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
var vignettePower = -2 * this.vignetteWeight;
effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
}
effect.setFloat("exposureLinear", this.exposure);
effect.setFloat("contrast", this.contrast);
if (this.colorGradingTexture) {
effect.setTexture("txColorTransform", this.colorGradingTexture);
var textureSize = this.colorGradingTexture.getSize().height;
effect.setFloat4(
"colorTransformSettings",
(textureSize - 1) / textureSize,
// textureScale
0.5 / textureSize,
// textureOffset
textureSize,
// textureSize
this.colorGradingTexture.level
// weight
);
}
};
ImageProcessingConfiguration2.prototype.clone = function() {
return BABYLON2.SerializationHelper.Clone(function() {
return new ImageProcessingConfiguration2();
}, this);
};
ImageProcessingConfiguration2.prototype.serialize = function() {
return BABYLON2.SerializationHelper.Serialize(this);
};
ImageProcessingConfiguration2.Parse = function(source) {
return BABYLON2.SerializationHelper.Parse(function() {
return new ImageProcessingConfiguration2();
}, source, null, null);
};
Object.defineProperty(ImageProcessingConfiguration2, "VIGNETTEMODE_MULTIPLY", {
/**
* Used to apply the vignette as a mix with the pixel color.
*/
get: function() {
return this._VIGNETTEMODE_MULTIPLY;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingConfiguration2, "VIGNETTEMODE_OPAQUE", {
/**
* Used to apply the vignette as a replacement of the pixel color.
*/
get: function() {
return this._VIGNETTEMODE_OPAQUE;
},
enumerable: true,
configurable: true
});
ImageProcessingConfiguration2.TONEMAPPING_STANDARD = 0;
ImageProcessingConfiguration2.TONEMAPPING_ACES = 1;
ImageProcessingConfiguration2._VIGNETTEMODE_MULTIPLY = 0;
ImageProcessingConfiguration2._VIGNETTEMODE_OPAQUE = 1;
__decorate([
BABYLON2.serializeAsColorCurves()
], ImageProcessingConfiguration2.prototype, "colorCurves", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_colorCurvesEnabled", void 0);
__decorate([
BABYLON2.serializeAsTexture("colorGradingTexture")
], ImageProcessingConfiguration2.prototype, "_colorGradingTexture", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_colorGradingEnabled", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_colorGradingWithGreenDepth", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_colorGradingBGR", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_exposure", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_toneMappingEnabled", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_toneMappingType", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_contrast", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "vignetteStretch", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "vignetteCentreX", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "vignetteCentreY", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "vignetteWeight", void 0);
__decorate([
BABYLON2.serializeAsColor4()
], ImageProcessingConfiguration2.prototype, "vignetteColor", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "vignetteCameraFov", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_vignetteBlendMode", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_vignetteEnabled", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_applyByPostProcess", void 0);
__decorate([
BABYLON2.serialize()
], ImageProcessingConfiguration2.prototype, "_isEnabled", void 0);
return ImageProcessingConfiguration2;
}()
);
BABYLON2.ImageProcessingConfiguration = ImageProcessingConfiguration;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ColorGradingTexture = (
/** @class */
function(_super) {
__extends(ColorGradingTexture2, _super);
function ColorGradingTexture2(url, scene) {
var _this = _super.call(this, scene) || this;
if (!url) {
return _this;
}
_this._engine = scene.getEngine();
_this._textureMatrix = BABYLON2.Matrix.Identity();
_this.name = url;
_this.url = url;
_this.hasAlpha = false;
_this.isCube = false;
_this.is3D = _this._engine.webGLVersion > 1;
_this.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.wrapR = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.anisotropicFilteringLevel = 1;
_this._texture = _this._getFromCache(url, true);
if (!_this._texture) {
if (!scene.useDelayedTextureLoading) {
_this.loadTexture();
} else {
_this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED;
}
}
return _this;
}
ColorGradingTexture2.prototype.getTextureMatrix = function() {
return this._textureMatrix;
};
ColorGradingTexture2.prototype.load3dlTexture = function() {
var engine = this._engine;
var texture;
if (engine.webGLVersion === 1) {
texture = engine.createRawTexture(null, 1, 1, BABYLON2.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
} else {
texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON2.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
}
this._texture = texture;
var callback = function(text) {
if (typeof text !== "string") {
return;
}
var data2 = null;
var tempData = null;
var line;
var lines = text.split("\n");
var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
var maxColor = 0;
for (var i2 = 0; i2 < lines.length; i2++) {
line = lines[i2];
if (!ColorGradingTexture2._noneEmptyLineRegex.test(line)) {
continue;
}
if (line.indexOf("#") === 0) {
continue;
}
var words = line.split(" ");
if (size === 0) {
size = words.length;
data2 = new Uint8Array(size * size * size * 4);
tempData = new Float32Array(size * size * size * 4);
continue;
}
if (size != 0) {
var r = Math.max(parseInt(words[0]), 0);
var g = Math.max(parseInt(words[1]), 0);
var b2 = Math.max(parseInt(words[2]), 0);
maxColor = Math.max(r, maxColor);
maxColor = Math.max(g, maxColor);
maxColor = Math.max(b2, maxColor);
var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
if (tempData) {
tempData[pixelStorageIndex + 0] = r;
tempData[pixelStorageIndex + 1] = g;
tempData[pixelStorageIndex + 2] = b2;
}
pixelIndexH++;
if (pixelIndexH % size == 0) {
pixelIndexSlice++;
pixelIndexH = 0;
if (pixelIndexSlice % size == 0) {
pixelIndexW++;
pixelIndexSlice = 0;
}
}
}
}
if (tempData && data2) {
for (var i2 = 0; i2 < tempData.length; i2++) {
if (i2 > 0 && (i2 + 1) % 4 === 0) {
data2[i2] = 255;
} else {
var value = tempData[i2];
data2[i2] = value / maxColor * 255;
}
}
}
if (texture.is3D) {
texture.updateSize(size, size, size);
engine.updateRawTexture3D(texture, data2, BABYLON2.Engine.TEXTUREFORMAT_RGBA, false);
} else {
texture.updateSize(size * size, size);
engine.updateRawTexture(texture, data2, BABYLON2.Engine.TEXTUREFORMAT_RGBA, false);
}
};
var scene = this.getScene();
if (scene) {
scene._loadFile(this.url, callback);
} else {
this._engine._loadFile(this.url, callback);
}
return this._texture;
};
ColorGradingTexture2.prototype.loadTexture = function() {
if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == this.url.length - 4) {
this.load3dlTexture();
}
};
ColorGradingTexture2.prototype.clone = function() {
var newTexture = new ColorGradingTexture2(this.url, this.getScene());
newTexture.level = this.level;
return newTexture;
};
ColorGradingTexture2.prototype.delayLoad = function() {
if (this.delayLoadState !== BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED) {
return;
}
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADED;
this._texture = this._getFromCache(this.url, true);
if (!this._texture) {
this.loadTexture();
}
};
ColorGradingTexture2.Parse = function(parsedTexture, scene, rootUrl) {
var texture = null;
if (parsedTexture.name && !parsedTexture.isRenderTarget) {
texture = new ColorGradingTexture2(parsedTexture.name, scene);
texture.name = parsedTexture.name;
texture.level = parsedTexture.level;
}
return texture;
};
ColorGradingTexture2.prototype.serialize = function() {
if (!this.name) {
return null;
}
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.level = this.level;
serializationObject.customType = "BABYLON.ColorGradingTexture";
return serializationObject;
};
ColorGradingTexture2._noneEmptyLineRegex = /\S+/;
return ColorGradingTexture2;
}(BABYLON2.BaseTexture)
);
BABYLON2.ColorGradingTexture = ColorGradingTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ColorCurves = (
/** @class */
function() {
function ColorCurves2() {
this._dirty = true;
this._tempColor = new BABYLON2.Color4(0, 0, 0, 0);
this._globalCurve = new BABYLON2.Color4(0, 0, 0, 0);
this._highlightsCurve = new BABYLON2.Color4(0, 0, 0, 0);
this._midtonesCurve = new BABYLON2.Color4(0, 0, 0, 0);
this._shadowsCurve = new BABYLON2.Color4(0, 0, 0, 0);
this._positiveCurve = new BABYLON2.Color4(0, 0, 0, 0);
this._negativeCurve = new BABYLON2.Color4(0, 0, 0, 0);
this._globalHue = 30;
this._globalDensity = 0;
this._globalSaturation = 0;
this._globalExposure = 0;
this._highlightsHue = 30;
this._highlightsDensity = 0;
this._highlightsSaturation = 0;
this._highlightsExposure = 0;
this._midtonesHue = 30;
this._midtonesDensity = 0;
this._midtonesSaturation = 0;
this._midtonesExposure = 0;
this._shadowsHue = 30;
this._shadowsDensity = 0;
this._shadowsSaturation = 0;
this._shadowsExposure = 0;
}
Object.defineProperty(ColorCurves2.prototype, "globalHue", {
/**
* Gets the global Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function() {
return this._globalHue;
},
/**
* Sets the global Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function(value) {
this._globalHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "globalDensity", {
/**
* Gets the global Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function() {
return this._globalDensity;
},
/**
* Sets the global Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function(value) {
this._globalDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "globalSaturation", {
/**
* Gets the global Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function() {
return this._globalSaturation;
},
/**
* Sets the global Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function(value) {
this._globalSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "globalExposure", {
/**
* Gets the global Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
get: function() {
return this._globalExposure;
},
/**
* Sets the global Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
set: function(value) {
this._globalExposure = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "highlightsHue", {
/**
* Gets the highlights Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function() {
return this._highlightsHue;
},
/**
* Sets the highlights Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function(value) {
this._highlightsHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "highlightsDensity", {
/**
* Gets the highlights Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function() {
return this._highlightsDensity;
},
/**
* Sets the highlights Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function(value) {
this._highlightsDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "highlightsSaturation", {
/**
* Gets the highlights Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function() {
return this._highlightsSaturation;
},
/**
* Sets the highlights Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function(value) {
this._highlightsSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "highlightsExposure", {
/**
* Gets the highlights Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
get: function() {
return this._highlightsExposure;
},
/**
* Sets the highlights Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
set: function(value) {
this._highlightsExposure = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "midtonesHue", {
/**
* Gets the midtones Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function() {
return this._midtonesHue;
},
/**
* Sets the midtones Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function(value) {
this._midtonesHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "midtonesDensity", {
/**
* Gets the midtones Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function() {
return this._midtonesDensity;
},
/**
* Sets the midtones Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function(value) {
this._midtonesDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "midtonesSaturation", {
/**
* Gets the midtones Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function() {
return this._midtonesSaturation;
},
/**
* Sets the midtones Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function(value) {
this._midtonesSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "midtonesExposure", {
/**
* Gets the midtones Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
get: function() {
return this._midtonesExposure;
},
/**
* Sets the midtones Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
set: function(value) {
this._midtonesExposure = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "shadowsHue", {
/**
* Gets the shadows Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
get: function() {
return this._shadowsHue;
},
/**
* Sets the shadows Hue value.
* The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
*/
set: function(value) {
this._shadowsHue = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "shadowsDensity", {
/**
* Gets the shadows Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
get: function() {
return this._shadowsDensity;
},
/**
* Sets the shadows Density value.
* The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
* Values less than zero provide a filter of opposite hue.
*/
set: function(value) {
this._shadowsDensity = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "shadowsSaturation", {
/**
* Gets the shadows Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
get: function() {
return this._shadowsSaturation;
},
/**
* Sets the shadows Saturation value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
*/
set: function(value) {
this._shadowsSaturation = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ColorCurves2.prototype, "shadowsExposure", {
/**
* Gets the shadows Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
get: function() {
return this._shadowsExposure;
},
/**
* Sets the shadows Exposure value.
* This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
*/
set: function(value) {
this._shadowsExposure = value;
this._dirty = true;
},
enumerable: true,
configurable: true
});
ColorCurves2.prototype.getClassName = function() {
return "ColorCurves";
};
ColorCurves2.Bind = function(colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
if (positiveUniform === void 0) {
positiveUniform = "vCameraColorCurvePositive";
}
if (neutralUniform === void 0) {
neutralUniform = "vCameraColorCurveNeutral";
}
if (negativeUniform === void 0) {
negativeUniform = "vCameraColorCurveNegative";
}
if (colorCurves._dirty) {
colorCurves._dirty = false;
colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
}
if (effect) {
effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
}
};
ColorCurves2.PrepareUniforms = function(uniformsList) {
uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
};
ColorCurves2.prototype.getColorGradingDataToRef = function(hue, density, saturation, exposure, result) {
if (hue == null) {
return;
}
hue = ColorCurves2.clamp(hue, 0, 360);
density = ColorCurves2.clamp(density, -100, 100);
saturation = ColorCurves2.clamp(saturation, -100, 100);
exposure = ColorCurves2.clamp(exposure, -100, 100);
density = ColorCurves2.applyColorGradingSliderNonlinear(density);
density *= 0.5;
exposure = ColorCurves2.applyColorGradingSliderNonlinear(exposure);
if (density < 0) {
density *= -1;
hue = (hue + 180) % 360;
}
ColorCurves2.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
result.scaleToRef(2, result);
result.a = 1 + 0.01 * saturation;
};
ColorCurves2.applyColorGradingSliderNonlinear = function(value) {
value /= 100;
var x = Math.abs(value);
x = Math.pow(x, 2);
if (value < 0) {
x *= -1;
}
x *= 100;
return x;
};
ColorCurves2.fromHSBToRef = function(hue, saturation, brightness, result) {
var h = ColorCurves2.clamp(hue, 0, 360);
var s = ColorCurves2.clamp(saturation / 100, 0, 1);
var v = ColorCurves2.clamp(brightness / 100, 0, 1);
if (s === 0) {
result.r = v;
result.g = v;
result.b = v;
} else {
h /= 60;
var i2 = Math.floor(h);
var f = h - i2;
var p = v * (1 - s);
var q = v * (1 - s * f);
var t = v * (1 - s * (1 - f));
switch (i2) {
case 0:
result.r = v;
result.g = t;
result.b = p;
break;
case 1:
result.r = q;
result.g = v;
result.b = p;
break;
case 2:
result.r = p;
result.g = v;
result.b = t;
break;
case 3:
result.r = p;
result.g = q;
result.b = v;
break;
case 4:
result.r = t;
result.g = p;
result.b = v;
break;
default:
result.r = v;
result.g = p;
result.b = q;
break;
}
}
result.a = 1;
};
ColorCurves2.clamp = function(value, min, max) {
return Math.min(Math.max(value, min), max);
};
ColorCurves2.prototype.clone = function() {
return BABYLON2.SerializationHelper.Clone(function() {
return new ColorCurves2();
}, this);
};
ColorCurves2.prototype.serialize = function() {
return BABYLON2.SerializationHelper.Serialize(this);
};
ColorCurves2.Parse = function(source) {
return BABYLON2.SerializationHelper.Parse(function() {
return new ColorCurves2();
}, source, null, null);
};
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_globalHue", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_globalDensity", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_globalSaturation", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_globalExposure", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_highlightsHue", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_highlightsDensity", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_highlightsSaturation", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_highlightsExposure", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_midtonesHue", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_midtonesDensity", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_midtonesSaturation", void 0);
__decorate([
BABYLON2.serialize()
], ColorCurves2.prototype, "_midtonesExposure", void 0);
return ColorCurves2;
}()
);
BABYLON2.ColorCurves = ColorCurves;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var RefractionPostProcess = (
/** @class */
function(_super) {
__extends(RefractionPostProcess2, _super);
function RefractionPostProcess2(name, refractionTextureUrl, color, depth, colorLevel, options, camera2, samplingMode, engine, reusable) {
var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera2, samplingMode, engine, reusable) || this;
_this.color = color;
_this.depth = depth;
_this.colorLevel = colorLevel;
_this._ownRefractionTexture = true;
_this.onActivateObservable.add(function(cam) {
_this._refTexture = _this._refTexture || new BABYLON2.Texture(refractionTextureUrl, cam.getScene());
});
_this.onApplyObservable.add(function(effect) {
effect.setColor3("baseColor", _this.color);
effect.setFloat("depth", _this.depth);
effect.setFloat("colorLevel", _this.colorLevel);
effect.setTexture("refractionSampler", _this._refTexture);
});
return _this;
}
Object.defineProperty(RefractionPostProcess2.prototype, "refractionTexture", {
/**
* Gets or sets the refraction texture
* Please note that you are responsible for disposing the texture if you set it manually
*/
get: function() {
return this._refTexture;
},
set: function(value) {
if (this._refTexture && this._ownRefractionTexture) {
this._refTexture.dispose();
}
this._refTexture = value;
this._ownRefractionTexture = false;
},
enumerable: true,
configurable: true
});
RefractionPostProcess2.prototype.dispose = function(camera2) {
if (this._refTexture && this._ownRefractionTexture) {
this._refTexture.dispose();
this._refTexture = null;
}
_super.prototype.dispose.call(this, camera2);
};
return RefractionPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.RefractionPostProcess = RefractionPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BlackAndWhitePostProcess = (
/** @class */
function(_super) {
__extends(BlackAndWhitePostProcess2, _super);
function BlackAndWhitePostProcess2(name, options, camera2, samplingMode, engine, reusable) {
var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera2, samplingMode, engine, reusable) || this;
_this.degree = 1;
_this.onApplyObservable.add(function(effect) {
effect.setFloat("degree", _this.degree);
});
return _this;
}
return BlackAndWhitePostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ConvolutionPostProcess = (
/** @class */
function(_super) {
__extends(ConvolutionPostProcess2, _super);
function ConvolutionPostProcess2(name, kernel, options, camera2, samplingMode, engine, reusable, textureType) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera2, samplingMode, engine, reusable, null, textureType) || this;
_this.kernel = kernel;
_this.onApply = function(effect) {
effect.setFloat2("screenSize", _this.width, _this.height);
effect.setArray("kernel", _this.kernel);
};
return _this;
}
ConvolutionPostProcess2.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
ConvolutionPostProcess2.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
ConvolutionPostProcess2.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
ConvolutionPostProcess2.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
ConvolutionPostProcess2.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
ConvolutionPostProcess2.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
return ConvolutionPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.ConvolutionPostProcess = ConvolutionPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FilterPostProcess = (
/** @class */
function(_super) {
__extends(FilterPostProcess2, _super);
function FilterPostProcess2(name, kernelMatrix, options, camera2, samplingMode, engine, reusable) {
var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera2, samplingMode, engine, reusable) || this;
_this.kernelMatrix = kernelMatrix;
_this.onApply = function(effect) {
effect.setMatrix("kernelMatrix", _this.kernelMatrix);
};
return _this;
}
return FilterPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.FilterPostProcess = FilterPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var VolumetricLightScatteringPostProcess = (
/** @class */
function(_super) {
__extends(VolumetricLightScatteringPostProcess2, _super);
function VolumetricLightScatteringPostProcess2(name, ratio, camera2, mesh2, samples, samplingMode, engine, reusable, scene) {
if (samples === void 0) {
samples = 100;
}
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.BILINEAR_SAMPLINGMODE;
}
var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera2, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
_this._screenCoordinates = BABYLON2.Vector2.Zero();
_this.customMeshPosition = BABYLON2.Vector3.Zero();
_this.useCustomMeshPosition = false;
_this.invert = true;
_this.excludedMeshes = new Array();
_this.exposure = 0.3;
_this.decay = 0.96815;
_this.weight = 0.58767;
_this.density = 0.926;
scene = camera2 === null ? scene : camera2.getScene();
engine = scene.getEngine();
_this._viewPort = new BABYLON2.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
_this.mesh = mesh2 !== null ? mesh2 : VolumetricLightScatteringPostProcess2.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
_this._createPass(scene, ratio.passRatio || ratio);
_this.onActivate = function(camera3) {
if (!_this.isSupported) {
_this.dispose(camera3);
}
_this.onActivate = null;
};
_this.onApplyObservable.add(function(effect) {
_this._updateMeshScreenCoordinates(scene);
effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
effect.setFloat("exposure", _this.exposure);
effect.setFloat("decay", _this.decay);
effect.setFloat("weight", _this.weight);
effect.setFloat("density", _this.density);
effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
});
return _this;
}
Object.defineProperty(VolumetricLightScatteringPostProcess2.prototype, "useDiffuseColor", {
/**
* @hidden
* VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
*/
get: function() {
BABYLON2.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
return false;
},
set: function(useDiffuseColor) {
BABYLON2.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
},
enumerable: true,
configurable: true
});
VolumetricLightScatteringPostProcess2.prototype.getClassName = function() {
return "VolumetricLightScatteringPostProcess";
};
VolumetricLightScatteringPostProcess2.prototype._isReady = function(subMesh, useInstances) {
var mesh2 = subMesh.getMesh();
if (mesh2 === this.mesh && mesh2.material) {
return mesh2.material.isReady(mesh2);
}
var defines = [];
var attribs = [BABYLON2.VertexBuffer.PositionKind];
var material = subMesh.getMaterial();
if (material) {
if (material.needAlphaTesting()) {
defines.push("#define ALPHATEST");
}
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
defines.push("#define UV1");
}
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind)) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
defines.push("#define UV2");
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
defines.push("#define BonesPerMesh " + (mesh2.skeleton ? mesh2.skeleton.bones.length + 1 : 0));
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
if (useInstances) {
defines.push("#define INSTANCES");
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._volumetricLightScatteringPass = mesh2.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
}
return this._volumetricLightScatteringPass.isReady();
};
VolumetricLightScatteringPostProcess2.prototype.setCustomMeshPosition = function(position) {
this.customMeshPosition = position;
};
VolumetricLightScatteringPostProcess2.prototype.getCustomMeshPosition = function() {
return this.customMeshPosition;
};
VolumetricLightScatteringPostProcess2.prototype.dispose = function(camera2) {
var rttIndex = camera2.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
if (rttIndex !== -1) {
camera2.getScene().customRenderTargets.splice(rttIndex, 1);
}
this._volumetricLightScatteringRTT.dispose();
_super.prototype.dispose.call(this, camera2);
};
VolumetricLightScatteringPostProcess2.prototype.getPass = function() {
return this._volumetricLightScatteringRTT;
};
VolumetricLightScatteringPostProcess2.prototype._meshExcluded = function(mesh2) {
if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh2) !== -1) {
return true;
}
return false;
};
VolumetricLightScatteringPostProcess2.prototype._createPass = function(scene, ratio) {
var _this = this;
var engine = scene.getEngine();
this._volumetricLightScatteringRTT = new BABYLON2.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this._volumetricLightScatteringRTT.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._volumetricLightScatteringRTT.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._volumetricLightScatteringRTT.renderList = null;
this._volumetricLightScatteringRTT.renderParticles = false;
this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
var camera2 = this.getCamera();
if (camera2) {
camera2.customRenderTargets.push(this._volumetricLightScatteringRTT);
} else {
scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
}
var renderSubMesh = function(subMesh) {
var mesh2 = subMesh.getRenderingMesh();
if (_this._meshExcluded(mesh2)) {
return;
}
var material = subMesh.getMaterial();
if (!material) {
return;
}
var scene2 = mesh2.getScene();
var engine2 = scene2.getEngine();
engine2.setState(material.backFaceCulling);
var batch = mesh2._getInstancesRenderList(subMesh._id);
if (batch.mustReturn) {
return;
}
var hardwareInstancedRendering = engine2.getCaps().instancedArrays && batch.visibleInstances[subMesh._id] !== null;
if (_this._isReady(subMesh, hardwareInstancedRendering)) {
var effect = _this._volumetricLightScatteringPass;
if (mesh2 === _this.mesh) {
if (subMesh.effect) {
effect = subMesh.effect;
} else {
effect = material.getEffect();
}
}
engine2.enableEffect(effect);
mesh2._bind(subMesh, effect, BABYLON2.Material.TriangleFillMode);
if (mesh2 === _this.mesh) {
material.bind(mesh2.getWorldMatrix(), mesh2);
} else {
_this._volumetricLightScatteringPass.setMatrix("viewProjection", scene2.getTransformMatrix());
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
_this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
if (alphaTexture) {
_this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
_this._volumetricLightScatteringPass.setMatrices("mBones", mesh2.skeleton.getTransformMatrices(mesh2));
}
}
mesh2._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON2.Material.TriangleFillMode, batch, hardwareInstancedRendering, function(isInstance, world) {
return effect.setMatrix("world", world);
});
}
};
var savedSceneClearColor;
var sceneClearColor = new BABYLON2.Color4(0, 0, 0, 1);
this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function() {
savedSceneClearColor = scene.clearColor;
scene.clearColor = sceneClearColor;
});
this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function() {
scene.clearColor = savedSceneClearColor;
});
this._volumetricLightScatteringRTT.customRenderFunction = function(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
var engine2 = scene.getEngine();
var index;
if (depthOnlySubMeshes.length) {
engine2.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
renderSubMesh(depthOnlySubMeshes.data[index]);
}
engine2.setColorWrite(true);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
renderSubMesh(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
renderSubMesh(alphaTestSubMeshes.data[index]);
}
if (transparentSubMeshes.length) {
for (index = 0; index < transparentSubMeshes.length; index++) {
var submesh = transparentSubMeshes.data[index];
var boundingInfo = submesh.getBoundingInfo();
if (boundingInfo && scene.activeCamera) {
submesh._alphaIndex = submesh.getMesh().alphaIndex;
submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
}
}
var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
sortedArray.sort(function(a, b2) {
if (a._alphaIndex > b2._alphaIndex) {
return 1;
}
if (a._alphaIndex < b2._alphaIndex) {
return -1;
}
if (a._distanceToCamera < b2._distanceToCamera) {
return 1;
}
if (a._distanceToCamera > b2._distanceToCamera) {
return -1;
}
return 0;
});
engine2.setAlphaMode(BABYLON2.Engine.ALPHA_COMBINE);
for (index = 0; index < sortedArray.length; index++) {
renderSubMesh(sortedArray[index]);
}
engine2.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
}
};
};
VolumetricLightScatteringPostProcess2.prototype._updateMeshScreenCoordinates = function(scene) {
var transform = scene.getTransformMatrix();
var meshPosition;
if (this.useCustomMeshPosition) {
meshPosition = this.customMeshPosition;
} else if (this.attachedNode) {
meshPosition = this.attachedNode.position;
} else {
meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
}
var pos = BABYLON2.Vector3.Project(meshPosition, BABYLON2.Matrix.Identity(), transform, this._viewPort);
this._screenCoordinates.x = pos.x / this._viewPort.width;
this._screenCoordinates.y = pos.y / this._viewPort.height;
if (this.invert) {
this._screenCoordinates.y = 1 - this._screenCoordinates.y;
}
};
VolumetricLightScatteringPostProcess2.CreateDefaultMesh = function(name, scene) {
var mesh2 = BABYLON2.Mesh.CreatePlane(name, 1, scene);
mesh2.billboardMode = BABYLON2.AbstractMesh.BILLBOARDMODE_ALL;
var material = new BABYLON2.StandardMaterial(name + "Material", scene);
material.emissiveColor = new BABYLON2.Color3(1, 1, 1);
mesh2.material = material;
return mesh2;
};
__decorate([
BABYLON2.serializeAsVector3()
], VolumetricLightScatteringPostProcess2.prototype, "customMeshPosition", void 0);
__decorate([
BABYLON2.serialize()
], VolumetricLightScatteringPostProcess2.prototype, "useCustomMeshPosition", void 0);
__decorate([
BABYLON2.serialize()
], VolumetricLightScatteringPostProcess2.prototype, "invert", void 0);
__decorate([
BABYLON2.serializeAsMeshReference()
], VolumetricLightScatteringPostProcess2.prototype, "mesh", void 0);
__decorate([
BABYLON2.serialize()
], VolumetricLightScatteringPostProcess2.prototype, "excludedMeshes", void 0);
__decorate([
BABYLON2.serialize()
], VolumetricLightScatteringPostProcess2.prototype, "exposure", void 0);
__decorate([
BABYLON2.serialize()
], VolumetricLightScatteringPostProcess2.prototype, "decay", void 0);
__decorate([
BABYLON2.serialize()
], VolumetricLightScatteringPostProcess2.prototype, "weight", void 0);
__decorate([
BABYLON2.serialize()
], VolumetricLightScatteringPostProcess2.prototype, "density", void 0);
return VolumetricLightScatteringPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ColorCorrectionPostProcess = (
/** @class */
function(_super) {
__extends(ColorCorrectionPostProcess2, _super);
function ColorCorrectionPostProcess2(name, colorTableUrl, options, camera2, samplingMode, engine, reusable) {
var _this = _super.call(this, name, "colorCorrection", null, ["colorTable"], options, camera2, samplingMode, engine, reusable) || this;
_this._colorTableTexture = new BABYLON2.Texture(colorTableUrl, camera2.getScene(), true, false, BABYLON2.Texture.TRILINEAR_SAMPLINGMODE);
_this._colorTableTexture.anisotropicFilteringLevel = 1;
_this._colorTableTexture.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this._colorTableTexture.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
_this.onApply = function(effect) {
effect.setTexture("colorTable", _this._colorTableTexture);
};
return _this;
}
return ColorCorrectionPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var TonemappingOperator;
(function(TonemappingOperator2) {
TonemappingOperator2[TonemappingOperator2["Hable"] = 0] = "Hable";
TonemappingOperator2[TonemappingOperator2["Reinhard"] = 1] = "Reinhard";
TonemappingOperator2[TonemappingOperator2["HejiDawson"] = 2] = "HejiDawson";
TonemappingOperator2[TonemappingOperator2["Photographic"] = 3] = "Photographic";
})(TonemappingOperator = BABYLON2.TonemappingOperator || (BABYLON2.TonemappingOperator = {}));
var TonemapPostProcess = (
/** @class */
function(_super) {
__extends(TonemapPostProcess2, _super);
function TonemapPostProcess2(name, _operator, exposureAdjustment, camera2, samplingMode, engine, textureFormat) {
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.BILINEAR_SAMPLINGMODE;
}
if (textureFormat === void 0) {
textureFormat = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1, camera2, samplingMode, engine, true, null, textureFormat) || this;
_this._operator = _operator;
_this.exposureAdjustment = exposureAdjustment;
var defines = "#define ";
if (_this._operator === TonemappingOperator.Hable) {
defines += "HABLE_TONEMAPPING";
} else if (_this._operator === TonemappingOperator.Reinhard) {
defines += "REINHARD_TONEMAPPING";
} else if (_this._operator === TonemappingOperator.HejiDawson) {
defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
} else if (_this._operator === TonemappingOperator.Photographic) {
defines += "PHOTOGRAPHIC_TONEMAPPING";
}
_this.updateEffect(defines);
_this.onApply = function(effect) {
effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
};
return _this;
}
return TonemapPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.TonemapPostProcess = TonemapPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DisplayPassPostProcess = (
/** @class */
function(_super) {
__extends(DisplayPassPostProcess2, _super);
function DisplayPassPostProcess2(name, options, camera2, samplingMode, engine, reusable) {
return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera2, samplingMode, engine, reusable) || this;
}
return DisplayPassPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.DisplayPassPostProcess = DisplayPassPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var HighlightsPostProcess = (
/** @class */
function(_super) {
__extends(HighlightsPostProcess2, _super);
function HighlightsPostProcess2(name, options, camera2, samplingMode, engine, reusable, textureType) {
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
return _super.call(this, name, "highlights", null, null, options, camera2, samplingMode, engine, reusable, null, textureType) || this;
}
return HighlightsPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.HighlightsPostProcess = HighlightsPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ImageProcessingPostProcess = (
/** @class */
function(_super) {
__extends(ImageProcessingPostProcess2, _super);
function ImageProcessingPostProcess2(name, options, camera2, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
if (camera2 === void 0) {
camera2 = null;
}
if (textureType === void 0) {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
var _this = _super.call(this, name, "imageProcessing", [], [], options, camera2, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
_this._fromLinearSpace = true;
_this._defines = {
IMAGEPROCESSING: false,
VIGNETTE: false,
VIGNETTEBLENDMODEMULTIPLY: false,
VIGNETTEBLENDMODEOPAQUE: false,
TONEMAPPING: false,
TONEMAPPING_ACES: false,
CONTRAST: false,
COLORCURVES: false,
COLORGRADING: false,
COLORGRADING3D: false,
FROMLINEARSPACE: false,
SAMPLER3DGREENDEPTH: false,
SAMPLER3DBGRMAP: false,
IMAGEPROCESSINGPOSTPROCESS: false,
EXPOSURE: false
};
if (imageProcessingConfiguration) {
imageProcessingConfiguration.applyByPostProcess = true;
_this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
_this.fromLinearSpace = false;
} else {
_this._attachImageProcessingConfiguration(null, true);
_this.imageProcessingConfiguration.applyByPostProcess = true;
}
_this.onApply = function(effect) {
_this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
};
return _this;
}
Object.defineProperty(ImageProcessingPostProcess2.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function() {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function(value) {
this._attachImageProcessingConfiguration(value);
},
enumerable: true,
configurable: true
});
ImageProcessingPostProcess2.prototype._attachImageProcessingConfiguration = function(configuration, doNotBuild) {
var _this = this;
if (doNotBuild === void 0) {
doNotBuild = false;
}
if (configuration === this._imageProcessingConfiguration) {
return;
}
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
if (!configuration) {
var scene = null;
var engine = this.getEngine();
var camera2 = this.getCamera();
if (camera2) {
scene = camera2.getScene();
} else if (engine && engine.scenes) {
var scenes = engine.scenes;
scene = scenes[scenes.length - 1];
} else {
scene = BABYLON2.Engine.LastCreatedScene;
}
this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
} else {
this._imageProcessingConfiguration = configuration;
}
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function(conf) {
_this._updateParameters();
});
}
if (!doNotBuild) {
this._updateParameters();
}
};
Object.defineProperty(ImageProcessingPostProcess2.prototype, "colorCurves", {
/**
* Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
*/
get: function() {
return this.imageProcessingConfiguration.colorCurves;
},
/**
* Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
*/
set: function(value) {
this.imageProcessingConfiguration.colorCurves = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "colorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "colorGradingTexture", {
/**
* Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
*/
get: function() {
return this.imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
*/
set: function(value) {
this.imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "colorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "exposure", {
/**
* Gets exposure used in the effect.
*/
get: function() {
return this.imageProcessingConfiguration.exposure;
},
/**
* Sets exposure used in the effect.
*/
set: function(value) {
this.imageProcessingConfiguration.exposure = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "toneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function() {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function(value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "contrast", {
/**
* Gets contrast used in the effect.
*/
get: function() {
return this.imageProcessingConfiguration.contrast;
},
/**
* Sets contrast used in the effect.
*/
set: function(value) {
this.imageProcessingConfiguration.contrast = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteStretch", {
/**
* Gets Vignette stretch size.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteStretch;
},
/**
* Sets Vignette stretch size.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteStretch = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteCentreX", {
/**
* Gets Vignette centre X Offset.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteCentreX;
},
/**
* Sets Vignette centre X Offset.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteCentreX = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteCentreY", {
/**
* Gets Vignette centre Y Offset.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteCentreY;
},
/**
* Sets Vignette centre Y Offset.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteCentreY = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteWeight", {
/**
* Gets Vignette weight or intensity of the vignette effect.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteWeight;
},
/**
* Sets Vignette weight or intensity of the vignette effect.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteWeight = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteColor", {
/**
* Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
* if vignetteEnabled is set to true.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteColor;
},
/**
* Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
* if vignetteEnabled is set to true.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteColor = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteCameraFov", {
/**
* Gets Camera field of view used by the Vignette effect.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteCameraFov;
},
/**
* Sets Camera field of view used by the Vignette effect.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteCameraFov = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteBlendMode", {
/**
* Gets the vignette blend mode allowing different kind of effect.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteBlendMode;
},
/**
* Sets the vignette blend mode allowing different kind of effect.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteBlendMode = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "vignetteEnabled", {
/**
* Gets wether the vignette effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.vignetteEnabled;
},
/**
* Sets wether the vignette effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.vignetteEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ImageProcessingPostProcess2.prototype, "fromLinearSpace", {
/**
* Gets wether the input of the processing is in Gamma or Linear Space.
*/
get: function() {
return this._fromLinearSpace;
},
/**
* Sets wether the input of the processing is in Gamma or Linear Space.
*/
set: function(value) {
if (this._fromLinearSpace === value) {
return;
}
this._fromLinearSpace = value;
this._updateParameters();
},
enumerable: true,
configurable: true
});
ImageProcessingPostProcess2.prototype.getClassName = function() {
return "ImageProcessingPostProcess";
};
ImageProcessingPostProcess2.prototype._updateParameters = function() {
this._defines.FROMLINEARSPACE = this._fromLinearSpace;
this.imageProcessingConfiguration.prepareDefines(this._defines, true);
var defines = "";
for (var define in this._defines) {
if (this._defines[define]) {
defines += "#define " + define + ";\r\n";
}
}
var samplers = ["textureSampler"];
var uniforms = ["scale"];
if (BABYLON2.ImageProcessingConfiguration) {
BABYLON2.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
BABYLON2.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
}
this.updateEffect(defines, uniforms, samplers);
};
ImageProcessingPostProcess2.prototype.dispose = function(camera2) {
_super.prototype.dispose.call(this, camera2);
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
if (this._imageProcessingConfiguration) {
this.imageProcessingConfiguration.applyByPostProcess = false;
}
};
__decorate([
BABYLON2.serialize()
], ImageProcessingPostProcess2.prototype, "_fromLinearSpace", void 0);
return ImageProcessingPostProcess2;
}(BABYLON2.PostProcess)
);
BABYLON2.ImageProcessingPostProcess = ImageProcessingPostProcess;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Bone = (
/** @class */
function(_super) {
__extends(Bone2, _super);
function Bone2(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
if (parentBone === void 0) {
parentBone = null;
}
if (localMatrix === void 0) {
localMatrix = null;
}
if (restPose === void 0) {
restPose = null;
}
if (baseMatrix === void 0) {
baseMatrix = null;
}
if (index === void 0) {
index = null;
}
var _this = _super.call(this, name, skeleton.getScene()) || this;
_this.name = name;
_this.children = new Array();
_this.animations = new Array();
_this._index = null;
_this._absoluteTransform = new BABYLON2.Matrix();
_this._invertedAbsoluteTransform = new BABYLON2.Matrix();
_this._scalingDeterminant = 1;
_this._worldTransform = new BABYLON2.Matrix();
_this._needToDecompose = true;
_this._needToCompose = false;
_this._skeleton = skeleton;
_this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON2.Matrix.Identity();
_this._restPose = restPose ? restPose : _this._localMatrix.clone();
_this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
_this._index = index;
skeleton.bones.push(_this);
_this.setParent(parentBone, false);
if (baseMatrix || localMatrix) {
_this._updateDifferenceMatrix();
}
return _this;
}
Object.defineProperty(Bone2.prototype, "_matrix", {
/** @hidden */
get: function() {
this._compose();
return this._localMatrix;
},
/** @hidden */
set: function(value) {
this._localMatrix.copyFrom(value);
this._needToDecompose = true;
},
enumerable: true,
configurable: true
});
Bone2.prototype.getSkeleton = function() {
return this._skeleton;
};
Bone2.prototype.getParent = function() {
return this._parent;
};
Bone2.prototype.setParent = function(parent, updateDifferenceMatrix) {
if (updateDifferenceMatrix === void 0) {
updateDifferenceMatrix = true;
}
if (this._parent === parent) {
return;
}
if (this._parent) {
var index = this._parent.children.indexOf(this);
if (index !== -1) {
this._parent.children.splice(index, 1);
}
}
this._parent = parent;
if (this._parent) {
this._parent.children.push(this);
}
if (updateDifferenceMatrix) {
this._updateDifferenceMatrix();
}
this.markAsDirty();
};
Bone2.prototype.getLocalMatrix = function() {
this._compose();
return this._localMatrix;
};
Bone2.prototype.getBaseMatrix = function() {
return this._baseMatrix;
};
Bone2.prototype.getRestPose = function() {
return this._restPose;
};
Bone2.prototype.getWorldMatrix = function() {
return this._worldTransform;
};
Bone2.prototype.returnToRest = function() {
this.updateMatrix(this._restPose.clone());
};
Bone2.prototype.getInvertedAbsoluteTransform = function() {
return this._invertedAbsoluteTransform;
};
Bone2.prototype.getAbsoluteTransform = function() {
return this._absoluteTransform;
};
Object.defineProperty(Bone2.prototype, "position", {
// Properties (matches AbstractMesh properties)
/** Gets or sets current position (in local space) */
get: function() {
this._decompose();
return this._localPosition;
},
set: function(newPosition) {
this._decompose();
this._localPosition.copyFrom(newPosition);
this._markAsDirtyAndCompose();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Bone2.prototype, "rotation", {
/** Gets or sets current rotation (in local space) */
get: function() {
return this.getRotation();
},
set: function(newRotation) {
this.setRotation(newRotation);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Bone2.prototype, "rotationQuaternion", {
/** Gets or sets current rotation quaternion (in local space) */
get: function() {
this._decompose();
return this._localRotation;
},
set: function(newRotation) {
this.setRotationQuaternion(newRotation);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Bone2.prototype, "scaling", {
/** Gets or sets current scaling (in local space) */
get: function() {
return this.getScale();
},
set: function(newScaling) {
this.setScale(newScaling);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Bone2.prototype, "animationPropertiesOverride", {
/**
* Gets the animation properties override
*/
get: function() {
return this._skeleton.animationPropertiesOverride;
},
enumerable: true,
configurable: true
});
Bone2.prototype._decompose = function() {
if (!this._needToDecompose) {
return;
}
this._needToDecompose = false;
if (!this._localScaling) {
this._localScaling = BABYLON2.Vector3.Zero();
this._localRotation = BABYLON2.Quaternion.Zero();
this._localPosition = BABYLON2.Vector3.Zero();
}
this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
};
Bone2.prototype._compose = function() {
if (!this._needToCompose) {
return;
}
this._needToCompose = false;
BABYLON2.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
};
Bone2.prototype.updateMatrix = function(matrix, updateDifferenceMatrix, updateLocalMatrix) {
if (updateDifferenceMatrix === void 0) {
updateDifferenceMatrix = true;
}
if (updateLocalMatrix === void 0) {
updateLocalMatrix = true;
}
this._baseMatrix.copyFrom(matrix);
if (updateDifferenceMatrix) {
this._updateDifferenceMatrix();
}
if (updateLocalMatrix) {
this._localMatrix.copyFrom(matrix);
this._markAsDirtyAndDecompose();
} else {
this.markAsDirty();
}
};
Bone2.prototype._updateDifferenceMatrix = function(rootMatrix, updateChildren) {
if (updateChildren === void 0) {
updateChildren = true;
}
if (!rootMatrix) {
rootMatrix = this._baseMatrix;
}
if (this._parent) {
rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
} else {
this._absoluteTransform.copyFrom(rootMatrix);
}
this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
if (updateChildren) {
for (var index = 0; index < this.children.length; index++) {
this.children[index]._updateDifferenceMatrix();
}
}
this._scalingDeterminant = this._absoluteTransform.determinant() < 0 ? -1 : 1;
};
Bone2.prototype.markAsDirty = function() {
this._currentRenderId++;
this._childRenderId++;
this._skeleton._markAsDirty();
};
Bone2.prototype._markAsDirtyAndCompose = function() {
this.markAsDirty();
this._needToCompose = true;
};
Bone2.prototype._markAsDirtyAndDecompose = function() {
this.markAsDirty();
this._needToDecompose = true;
};
Bone2.prototype.copyAnimationRange = function(source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
if (rescaleAsRequired === void 0) {
rescaleAsRequired = false;
}
if (skelDimensionsRatio === void 0) {
skelDimensionsRatio = null;
}
if (this.animations.length === 0) {
this.animations.push(new BABYLON2.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON2.Animation.ANIMATIONTYPE_MATRIX, 0));
this.animations[0].setKeys([]);
}
var sourceRange = source.animations[0].getRange(rangeName);
if (!sourceRange) {
return false;
}
var from = sourceRange.from;
var to = sourceRange.to;
var sourceKeys = source.animations[0].getKeys();
var sourceBoneLength = source.length;
var sourceParent = source.getParent();
var parent = this.getParent();
var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
var destKeys = this.animations[0].getKeys();
var orig;
var origTranslation;
var mat;
for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
orig = sourceKeys[key];
if (orig.frame >= from && orig.frame <= to) {
if (rescaleAsRequired) {
mat = orig.value.clone();
if (parentScalingReqd) {
origTranslation = mat.getTranslation();
mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
} else if (dimensionsScalingReqd && skelDimensionsRatio) {
origTranslation = mat.getTranslation();
mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
} else {
mat = orig.value;
}
} else {
mat = orig.value;
}
destKeys.push({ frame: orig.frame + frameOffset, value: mat });
}
}
this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
return true;
};
Bone2.prototype.translate = function(vec, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
var lm = this.getLocalMatrix();
if (space == BABYLON2.Space.LOCAL) {
lm.m[12] += vec.x;
lm.m[13] += vec.y;
lm.m[14] += vec.z;
} else {
var wm = null;
if (mesh2) {
wm = mesh2.getWorldMatrix();
}
this._skeleton.computeAbsoluteTransforms();
var tmat = Bone2._tmpMats[0];
var tvec = Bone2._tmpVecs[0];
if (this._parent) {
if (mesh2 && wm) {
tmat.copyFrom(this._parent.getAbsoluteTransform());
tmat.multiplyToRef(wm, tmat);
} else {
tmat.copyFrom(this._parent.getAbsoluteTransform());
}
}
tmat.m[12] = 0;
tmat.m[13] = 0;
tmat.m[14] = 0;
tmat.invert();
BABYLON2.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
lm.m[12] += tvec.x;
lm.m[13] += tvec.y;
lm.m[14] += tvec.z;
}
this._markAsDirtyAndDecompose();
};
Bone2.prototype.setPosition = function(position, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
var lm = this.getLocalMatrix();
if (space == BABYLON2.Space.LOCAL) {
lm.m[12] = position.x;
lm.m[13] = position.y;
lm.m[14] = position.z;
} else {
var wm = null;
if (mesh2) {
wm = mesh2.getWorldMatrix();
}
this._skeleton.computeAbsoluteTransforms();
var tmat = Bone2._tmpMats[0];
var vec = Bone2._tmpVecs[0];
if (this._parent) {
if (mesh2 && wm) {
tmat.copyFrom(this._parent.getAbsoluteTransform());
tmat.multiplyToRef(wm, tmat);
} else {
tmat.copyFrom(this._parent.getAbsoluteTransform());
}
}
tmat.invert();
BABYLON2.Vector3.TransformCoordinatesToRef(position, tmat, vec);
lm.m[12] = vec.x;
lm.m[13] = vec.y;
lm.m[14] = vec.z;
}
this._markAsDirtyAndDecompose();
};
Bone2.prototype.setAbsolutePosition = function(position, mesh2) {
this.setPosition(position, BABYLON2.Space.WORLD, mesh2);
};
Bone2.prototype.scale = function(x, y, z, scaleChildren) {
if (scaleChildren === void 0) {
scaleChildren = false;
}
var locMat = this.getLocalMatrix();
var scaleMat = Bone2._tmpMats[0];
BABYLON2.Matrix.ScalingToRef(x, y, z, scaleMat);
scaleMat.multiplyToRef(locMat, locMat);
scaleMat.invert();
for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
var child = _a[_i];
var cm = child.getLocalMatrix();
cm.multiplyToRef(scaleMat, cm);
cm.m[12] *= x;
cm.m[13] *= y;
cm.m[14] *= z;
child._markAsDirtyAndDecompose();
}
this._markAsDirtyAndDecompose();
if (scaleChildren) {
for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
var child = _c[_b];
child.scale(x, y, z, scaleChildren);
}
}
};
Bone2.prototype.setScale = function(scale) {
this._decompose();
this._localScaling.copyFrom(scale);
this._markAsDirtyAndCompose();
};
Bone2.prototype.getScale = function() {
this._decompose();
return this._localScaling;
};
Bone2.prototype.getScaleToRef = function(result) {
this._decompose();
result.copyFrom(this._localScaling);
};
Bone2.prototype.setYawPitchRoll = function(yaw, pitch, roll, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (space === BABYLON2.Space.LOCAL) {
var quat = Bone2._tmpQuat;
BABYLON2.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
this.setRotationQuaternion(quat, space, mesh2);
return;
}
var rotMatInv = Bone2._tmpMats[0];
if (!this._getNegativeRotationToRef(rotMatInv, mesh2)) {
return;
}
var rotMat = Bone2._tmpMats[1];
BABYLON2.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
rotMatInv.multiplyToRef(rotMat, rotMat);
this._rotateWithMatrix(rotMat, space, mesh2);
};
Bone2.prototype.rotate = function(axis, amount, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
var rmat = Bone2._tmpMats[0];
rmat.m[12] = 0;
rmat.m[13] = 0;
rmat.m[14] = 0;
BABYLON2.Matrix.RotationAxisToRef(axis, amount, rmat);
this._rotateWithMatrix(rmat, space, mesh2);
};
Bone2.prototype.setAxisAngle = function(axis, angle, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (space === BABYLON2.Space.LOCAL) {
var quat = Bone2._tmpQuat;
BABYLON2.Quaternion.RotationAxisToRef(axis, angle, quat);
this.setRotationQuaternion(quat, space, mesh2);
return;
}
var rotMatInv = Bone2._tmpMats[0];
if (!this._getNegativeRotationToRef(rotMatInv, mesh2)) {
return;
}
var rotMat = Bone2._tmpMats[1];
BABYLON2.Matrix.RotationAxisToRef(axis, angle, rotMat);
rotMatInv.multiplyToRef(rotMat, rotMat);
this._rotateWithMatrix(rotMat, space, mesh2);
};
Bone2.prototype.setRotation = function(rotation, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh2);
};
Bone2.prototype.setRotationQuaternion = function(quat, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (space === BABYLON2.Space.LOCAL) {
this._decompose();
this._localRotation.copyFrom(quat);
this._markAsDirtyAndCompose();
return;
}
var rotMatInv = Bone2._tmpMats[0];
if (!this._getNegativeRotationToRef(rotMatInv, mesh2)) {
return;
}
var rotMat = Bone2._tmpMats[1];
BABYLON2.Matrix.FromQuaternionToRef(quat, rotMat);
rotMatInv.multiplyToRef(rotMat, rotMat);
this._rotateWithMatrix(rotMat, space, mesh2);
};
Bone2.prototype.setRotationMatrix = function(rotMat, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (space === BABYLON2.Space.LOCAL) {
var quat = Bone2._tmpQuat;
BABYLON2.Quaternion.FromRotationMatrixToRef(rotMat, quat);
this.setRotationQuaternion(quat, space, mesh2);
return;
}
var rotMatInv = Bone2._tmpMats[0];
if (!this._getNegativeRotationToRef(rotMatInv, mesh2)) {
return;
}
var rotMat2 = Bone2._tmpMats[1];
rotMat2.copyFrom(rotMat);
rotMatInv.multiplyToRef(rotMat, rotMat2);
this._rotateWithMatrix(rotMat2, space, mesh2);
};
Bone2.prototype._rotateWithMatrix = function(rmat, space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
var lmat = this.getLocalMatrix();
var lx = lmat.m[12];
var ly = lmat.m[13];
var lz = lmat.m[14];
var parent = this.getParent();
var parentScale = Bone2._tmpMats[3];
var parentScaleInv = Bone2._tmpMats[4];
if (parent && space == BABYLON2.Space.WORLD) {
if (mesh2) {
parentScale.copyFrom(mesh2.getWorldMatrix());
parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
} else {
parentScale.copyFrom(parent.getAbsoluteTransform());
}
parentScaleInv.copyFrom(parentScale);
parentScaleInv.invert();
lmat.multiplyToRef(parentScale, lmat);
lmat.multiplyToRef(rmat, lmat);
lmat.multiplyToRef(parentScaleInv, lmat);
} else {
if (space == BABYLON2.Space.WORLD && mesh2) {
parentScale.copyFrom(mesh2.getWorldMatrix());
parentScaleInv.copyFrom(parentScale);
parentScaleInv.invert();
lmat.multiplyToRef(parentScale, lmat);
lmat.multiplyToRef(rmat, lmat);
lmat.multiplyToRef(parentScaleInv, lmat);
} else {
lmat.multiplyToRef(rmat, lmat);
}
}
lmat.m[12] = lx;
lmat.m[13] = ly;
lmat.m[14] = lz;
this.computeAbsoluteTransforms();
this._markAsDirtyAndDecompose();
};
Bone2.prototype._getNegativeRotationToRef = function(rotMatInv, mesh2) {
var scaleMatrix = Bone2._tmpMats[2];
rotMatInv.copyFrom(this.getAbsoluteTransform());
if (mesh2) {
rotMatInv.multiplyToRef(mesh2.getWorldMatrix(), rotMatInv);
BABYLON2.Matrix.ScalingToRef(mesh2.scaling.x, mesh2.scaling.y, mesh2.scaling.z, scaleMatrix);
}
rotMatInv.invert();
if (isNaN(rotMatInv.m[0])) {
return false;
}
scaleMatrix.m[0] *= this._scalingDeterminant;
rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
return true;
};
Bone2.prototype.getPosition = function(space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (mesh2 === void 0) {
mesh2 = null;
}
var pos = BABYLON2.Vector3.Zero();
this.getPositionToRef(space, mesh2, pos);
return pos;
};
Bone2.prototype.getPositionToRef = function(space, mesh2, result) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (space == BABYLON2.Space.LOCAL) {
var lm = this.getLocalMatrix();
result.x = lm.m[12];
result.y = lm.m[13];
result.z = lm.m[14];
} else {
var wm = null;
if (mesh2) {
wm = mesh2.getWorldMatrix();
}
this._skeleton.computeAbsoluteTransforms();
var tmat = Bone2._tmpMats[0];
if (mesh2 && wm) {
tmat.copyFrom(this.getAbsoluteTransform());
tmat.multiplyToRef(wm, tmat);
} else {
tmat = this.getAbsoluteTransform();
}
result.x = tmat.m[12];
result.y = tmat.m[13];
result.z = tmat.m[14];
}
};
Bone2.prototype.getAbsolutePosition = function(mesh2) {
if (mesh2 === void 0) {
mesh2 = null;
}
var pos = BABYLON2.Vector3.Zero();
this.getPositionToRef(BABYLON2.Space.WORLD, mesh2, pos);
return pos;
};
Bone2.prototype.getAbsolutePositionToRef = function(mesh2, result) {
this.getPositionToRef(BABYLON2.Space.WORLD, mesh2, result);
};
Bone2.prototype.computeAbsoluteTransforms = function() {
this._compose();
if (this._parent) {
this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
} else {
this._absoluteTransform.copyFrom(this._localMatrix);
var poseMatrix = this._skeleton.getPoseMatrix();
if (poseMatrix) {
this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
}
}
var children = this.children;
var len = children.length;
for (var i2 = 0; i2 < len; i2++) {
children[i2].computeAbsoluteTransforms();
}
};
Bone2.prototype.getDirection = function(localAxis, mesh2) {
if (mesh2 === void 0) {
mesh2 = null;
}
var result = BABYLON2.Vector3.Zero();
this.getDirectionToRef(localAxis, mesh2, result);
return result;
};
Bone2.prototype.getDirectionToRef = function(localAxis, mesh2, result) {
if (mesh2 === void 0) {
mesh2 = null;
}
var wm = null;
if (mesh2) {
wm = mesh2.getWorldMatrix();
}
this._skeleton.computeAbsoluteTransforms();
var mat = Bone2._tmpMats[0];
mat.copyFrom(this.getAbsoluteTransform());
if (mesh2 && wm) {
mat.multiplyToRef(wm, mat);
}
BABYLON2.Vector3.TransformNormalToRef(localAxis, mat, result);
result.normalize();
};
Bone2.prototype.getRotation = function(space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (mesh2 === void 0) {
mesh2 = null;
}
var result = BABYLON2.Vector3.Zero();
this.getRotationToRef(space, mesh2, result);
return result;
};
Bone2.prototype.getRotationToRef = function(space, mesh2, result) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (mesh2 === void 0) {
mesh2 = null;
}
var quat = Bone2._tmpQuat;
this.getRotationQuaternionToRef(space, mesh2, quat);
quat.toEulerAnglesToRef(result);
};
Bone2.prototype.getRotationQuaternion = function(space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (mesh2 === void 0) {
mesh2 = null;
}
var result = BABYLON2.Quaternion.Identity();
this.getRotationQuaternionToRef(space, mesh2, result);
return result;
};
Bone2.prototype.getRotationQuaternionToRef = function(space, mesh2, result) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (mesh2 === void 0) {
mesh2 = null;
}
if (space == BABYLON2.Space.LOCAL) {
this._decompose();
result.copyFrom(this._localRotation);
} else {
var mat = Bone2._tmpMats[0];
var amat = this.getAbsoluteTransform();
if (mesh2) {
amat.multiplyToRef(mesh2.getWorldMatrix(), mat);
} else {
mat.copyFrom(amat);
}
mat.m[0] *= this._scalingDeterminant;
mat.m[1] *= this._scalingDeterminant;
mat.m[2] *= this._scalingDeterminant;
mat.decompose(void 0, result, void 0);
}
};
Bone2.prototype.getRotationMatrix = function(space, mesh2) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
var result = BABYLON2.Matrix.Identity();
this.getRotationMatrixToRef(space, mesh2, result);
return result;
};
Bone2.prototype.getRotationMatrixToRef = function(space, mesh2, result) {
if (space === void 0) {
space = BABYLON2.Space.LOCAL;
}
if (space == BABYLON2.Space.LOCAL) {
this.getLocalMatrix().getRotationMatrixToRef(result);
} else {
var mat = Bone2._tmpMats[0];
var amat = this.getAbsoluteTransform();
if (mesh2) {
amat.multiplyToRef(mesh2.getWorldMatrix(), mat);
} else {
mat.copyFrom(amat);
}
mat.m[0] *= this._scalingDeterminant;
mat.m[1] *= this._scalingDeterminant;
mat.m[2] *= this._scalingDeterminant;
mat.getRotationMatrixToRef(result);
}
};
Bone2.prototype.getAbsolutePositionFromLocal = function(position, mesh2) {
if (mesh2 === void 0) {
mesh2 = null;
}
var result = BABYLON2.Vector3.Zero();
this.getAbsolutePositionFromLocalToRef(position, mesh2, result);
return result;
};
Bone2.prototype.getAbsolutePositionFromLocalToRef = function(position, mesh2, result) {
if (mesh2 === void 0) {
mesh2 = null;
}
var wm = null;
if (mesh2) {
wm = mesh2.getWorldMatrix();
}
this._skeleton.computeAbsoluteTransforms();
var tmat = Bone2._tmpMats[0];
if (mesh2 && wm) {
tmat.copyFrom(this.getAbsoluteTransform());
tmat.multiplyToRef(wm, tmat);
} else {
tmat = this.getAbsoluteTransform();
}
BABYLON2.Vector3.TransformCoordinatesToRef(position, tmat, result);
};
Bone2.prototype.getLocalPositionFromAbsolute = function(position, mesh2) {
if (mesh2 === void 0) {
mesh2 = null;
}
var result = BABYLON2.Vector3.Zero();
this.getLocalPositionFromAbsoluteToRef(position, mesh2, result);
return result;
};
Bone2.prototype.getLocalPositionFromAbsoluteToRef = function(position, mesh2, result) {
if (mesh2 === void 0) {
mesh2 = null;
}
var wm = null;
if (mesh2) {
wm = mesh2.getWorldMatrix();
}
this._skeleton.computeAbsoluteTransforms();
var tmat = Bone2._tmpMats[0];
tmat.copyFrom(this.getAbsoluteTransform());
if (mesh2 && wm) {
tmat.multiplyToRef(wm, tmat);
}
tmat.invert();
BABYLON2.Vector3.TransformCoordinatesToRef(position, tmat, result);
};
Bone2._tmpVecs = [BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero()];
Bone2._tmpQuat = BABYLON2.Quaternion.Identity();
Bone2._tmpMats = [BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity()];
return Bone2;
}(BABYLON2.Node)
);
BABYLON2.Bone = Bone;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BoneIKController = (
/** @class */
function() {
function BoneIKController2(mesh2, bone, options) {
this.targetPosition = BABYLON2.Vector3.Zero();
this.poleTargetPosition = BABYLON2.Vector3.Zero();
this.poleTargetLocalOffset = BABYLON2.Vector3.Zero();
this.poleAngle = 0;
this.slerpAmount = 1;
this._bone1Quat = BABYLON2.Quaternion.Identity();
this._bone1Mat = BABYLON2.Matrix.Identity();
this._bone2Ang = Math.PI;
this._maxAngle = Math.PI;
this._rightHandedSystem = false;
this._bendAxis = BABYLON2.Vector3.Right();
this._slerping = false;
this._adjustRoll = 0;
this._bone2 = bone;
this._bone1 = bone.getParent();
if (!this._bone1) {
return;
}
this.mesh = mesh2;
var bonePos = bone.getPosition();
if (bone.getAbsoluteTransform().determinant() > 0) {
this._rightHandedSystem = true;
this._bendAxis.x = 0;
this._bendAxis.y = 0;
this._bendAxis.z = -1;
if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
this._adjustRoll = Math.PI * 0.5;
this._bendAxis.z = 1;
}
}
if (this._bone1.length) {
var boneScale1 = this._bone1.getScale();
var boneScale2 = this._bone2.getScale();
this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
} else if (this._bone1.children[0]) {
mesh2.computeWorldMatrix(true);
var pos1 = this._bone2.children[0].getAbsolutePosition(mesh2);
var pos2 = this._bone2.getAbsolutePosition(mesh2);
var pos3 = this._bone1.getAbsolutePosition(mesh2);
this._bone1Length = BABYLON2.Vector3.Distance(pos1, pos2);
this._bone2Length = BABYLON2.Vector3.Distance(pos2, pos3);
}
this._bone1.getRotationMatrixToRef(BABYLON2.Space.WORLD, mesh2, this._bone1Mat);
this.maxAngle = Math.PI;
if (options) {
if (options.targetMesh) {
this.targetMesh = options.targetMesh;
this.targetMesh.computeWorldMatrix(true);
}
if (options.poleTargetMesh) {
this.poleTargetMesh = options.poleTargetMesh;
this.poleTargetMesh.computeWorldMatrix(true);
} else if (options.poleTargetBone) {
this.poleTargetBone = options.poleTargetBone;
} else if (this._bone1.getParent()) {
this.poleTargetBone = this._bone1.getParent();
}
if (options.poleTargetLocalOffset) {
this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
}
if (options.poleAngle) {
this.poleAngle = options.poleAngle;
}
if (options.bendAxis) {
this._bendAxis.copyFrom(options.bendAxis);
}
if (options.maxAngle) {
this.maxAngle = options.maxAngle;
}
if (options.slerpAmount) {
this.slerpAmount = options.slerpAmount;
}
}
}
Object.defineProperty(BoneIKController2.prototype, "maxAngle", {
/**
* Gets or sets maximum allowed angle
*/
get: function() {
return this._maxAngle;
},
set: function(value) {
this._setMaxAngle(value);
},
enumerable: true,
configurable: true
});
BoneIKController2.prototype._setMaxAngle = function(ang) {
if (ang < 0) {
ang = 0;
}
if (ang > Math.PI || ang == void 0) {
ang = Math.PI;
}
this._maxAngle = ang;
var a = this._bone1Length;
var b2 = this._bone2Length;
this._maxReach = Math.sqrt(a * a + b2 * b2 - 2 * a * b2 * Math.cos(ang));
};
BoneIKController2.prototype.update = function() {
var bone1 = this._bone1;
if (!bone1) {
return;
}
var target = this.targetPosition;
var poleTarget = this.poleTargetPosition;
var mat1 = BoneIKController2._tmpMats[0];
var mat2 = BoneIKController2._tmpMats[1];
if (this.targetMesh) {
target.copyFrom(this.targetMesh.getAbsolutePosition());
}
if (this.poleTargetBone) {
this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
} else if (this.poleTargetMesh) {
BABYLON2.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
}
var bonePos = BoneIKController2._tmpVecs[0];
var zaxis = BoneIKController2._tmpVecs[1];
var xaxis = BoneIKController2._tmpVecs[2];
var yaxis = BoneIKController2._tmpVecs[3];
var upAxis = BoneIKController2._tmpVecs[4];
var _tmpQuat = BoneIKController2._tmpQuat;
bone1.getAbsolutePositionToRef(this.mesh, bonePos);
poleTarget.subtractToRef(bonePos, upAxis);
if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
upAxis.y = 1;
} else {
upAxis.normalize();
}
target.subtractToRef(bonePos, yaxis);
yaxis.normalize();
BABYLON2.Vector3.CrossToRef(yaxis, upAxis, zaxis);
zaxis.normalize();
BABYLON2.Vector3.CrossToRef(yaxis, zaxis, xaxis);
xaxis.normalize();
BABYLON2.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
var a = this._bone1Length;
var b2 = this._bone2Length;
var c = BABYLON2.Vector3.Distance(bonePos, target);
if (this._maxReach > 0) {
c = Math.min(this._maxReach, c);
}
var acosa = (b2 * b2 + c * c - a * a) / (2 * b2 * c);
var acosb = (c * c + a * a - b2 * b2) / (2 * c * a);
if (acosa > 1) {
acosa = 1;
}
if (acosb > 1) {
acosb = 1;
}
if (acosa < -1) {
acosa = -1;
}
if (acosb < -1) {
acosb = -1;
}
var angA = Math.acos(acosa);
var angB = Math.acos(acosb);
var angC = -angA - angB;
if (this._rightHandedSystem) {
BABYLON2.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
mat2.multiplyToRef(mat1, mat1);
BABYLON2.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
mat2.multiplyToRef(mat1, mat1);
} else {
var _tmpVec = BoneIKController2._tmpVecs[5];
_tmpVec.copyFrom(this._bendAxis);
_tmpVec.x *= -1;
BABYLON2.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
mat2.multiplyToRef(mat1, mat1);
}
if (this.poleAngle) {
BABYLON2.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
mat1.multiplyToRef(mat2, mat1);
}
if (this._bone1) {
if (this.slerpAmount < 1) {
if (!this._slerping) {
BABYLON2.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
}
BABYLON2.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
BABYLON2.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
angC = this._bone2Ang * (1 - this.slerpAmount) + angC * this.slerpAmount;
this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON2.Space.WORLD, this.mesh);
this._slerping = true;
} else {
this._bone1.setRotationMatrix(mat1, BABYLON2.Space.WORLD, this.mesh);
this._bone1Mat.copyFrom(mat1);
this._slerping = false;
}
}
this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON2.Space.LOCAL);
this._bone2Ang = angC;
};
BoneIKController2._tmpVecs = [BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero()];
BoneIKController2._tmpQuat = BABYLON2.Quaternion.Identity();
BoneIKController2._tmpMats = [BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity()];
return BoneIKController2;
}()
);
BABYLON2.BoneIKController = BoneIKController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BoneLookController = (
/** @class */
function() {
function BoneLookController2(mesh2, bone, target, options) {
this.upAxis = BABYLON2.Vector3.Up();
this.upAxisSpace = BABYLON2.Space.LOCAL;
this.adjustYaw = 0;
this.adjustPitch = 0;
this.adjustRoll = 0;
this.slerpAmount = 1;
this._boneQuat = BABYLON2.Quaternion.Identity();
this._slerping = false;
this._firstFrameSkipped = false;
this._fowardAxis = BABYLON2.Vector3.Forward();
this.mesh = mesh2;
this.bone = bone;
this.target = target;
if (options) {
if (options.adjustYaw) {
this.adjustYaw = options.adjustYaw;
}
if (options.adjustPitch) {
this.adjustPitch = options.adjustPitch;
}
if (options.adjustRoll) {
this.adjustRoll = options.adjustRoll;
}
if (options.maxYaw != null) {
this.maxYaw = options.maxYaw;
} else {
this.maxYaw = Math.PI;
}
if (options.minYaw != null) {
this.minYaw = options.minYaw;
} else {
this.minYaw = -Math.PI;
}
if (options.maxPitch != null) {
this.maxPitch = options.maxPitch;
} else {
this.maxPitch = Math.PI;
}
if (options.minPitch != null) {
this.minPitch = options.minPitch;
} else {
this.minPitch = -Math.PI;
}
if (options.slerpAmount != null) {
this.slerpAmount = options.slerpAmount;
}
if (options.upAxis != null) {
this.upAxis = options.upAxis;
}
if (options.upAxisSpace != null) {
this.upAxisSpace = options.upAxisSpace;
}
if (options.yawAxis != null || options.pitchAxis != null) {
var newYawAxis = BABYLON2.Axis.Y;
var newPitchAxis = BABYLON2.Axis.X;
if (options.yawAxis != null) {
newYawAxis = options.yawAxis.clone();
newYawAxis.normalize();
}
if (options.pitchAxis != null) {
newPitchAxis = options.pitchAxis.clone();
newPitchAxis.normalize();
}
var newRollAxis = BABYLON2.Vector3.Cross(newPitchAxis, newYawAxis);
this._transformYawPitch = BABYLON2.Matrix.Identity();
BABYLON2.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
this._transformYawPitchInv = this._transformYawPitch.clone();
this._transformYawPitch.invert();
}
}
if (!bone.getParent() && this.upAxisSpace == BABYLON2.Space.BONE) {
this.upAxisSpace = BABYLON2.Space.LOCAL;
}
}
Object.defineProperty(BoneLookController2.prototype, "minYaw", {
/**
* Gets or sets the minimum yaw angle that the bone can look to
*/
get: function() {
return this._minYaw;
},
set: function(value) {
this._minYaw = value;
this._minYawSin = Math.sin(value);
this._minYawCos = Math.cos(value);
if (this._maxYaw != null) {
this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;
this._yawRange = this._maxYaw - this._minYaw;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BoneLookController2.prototype, "maxYaw", {
/**
* Gets or sets the maximum yaw angle that the bone can look to
*/
get: function() {
return this._maxYaw;
},
set: function(value) {
this._maxYaw = value;
this._maxYawSin = Math.sin(value);
this._maxYawCos = Math.cos(value);
if (this._minYaw != null) {
this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * 0.5 + this._minYaw;
this._yawRange = this._maxYaw - this._minYaw;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BoneLookController2.prototype, "minPitch", {
/**
* Gets or sets the minimum pitch angle that the bone can look to
*/
get: function() {
return this._minPitch;
},
set: function(value) {
this._minPitch = value;
this._minPitchTan = Math.tan(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(BoneLookController2.prototype, "maxPitch", {
/**
* Gets or sets the maximum pitch angle that the bone can look to
*/
get: function() {
return this._maxPitch;
},
set: function(value) {
this._maxPitch = value;
this._maxPitchTan = Math.tan(value);
},
enumerable: true,
configurable: true
});
BoneLookController2.prototype.update = function() {
if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
this._firstFrameSkipped = true;
return;
}
var bone = this.bone;
var bonePos = BoneLookController2._tmpVecs[0];
bone.getAbsolutePositionToRef(this.mesh, bonePos);
var target = this.target;
var _tmpMat1 = BoneLookController2._tmpMats[0];
var _tmpMat2 = BoneLookController2._tmpMats[1];
var mesh2 = this.mesh;
var parentBone = bone.getParent();
var upAxis = BoneLookController2._tmpVecs[1];
upAxis.copyFrom(this.upAxis);
if (this.upAxisSpace == BABYLON2.Space.BONE && parentBone) {
if (this._transformYawPitch) {
BABYLON2.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
}
parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
} else if (this.upAxisSpace == BABYLON2.Space.LOCAL) {
mesh2.getDirectionToRef(upAxis, upAxis);
if (mesh2.scaling.x != 1 || mesh2.scaling.y != 1 || mesh2.scaling.z != 1) {
upAxis.normalize();
}
}
var checkYaw = false;
var checkPitch = false;
if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
checkYaw = true;
}
if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
checkPitch = true;
}
if (checkYaw || checkPitch) {
var spaceMat = BoneLookController2._tmpMats[2];
var spaceMatInv = BoneLookController2._tmpMats[3];
if (this.upAxisSpace == BABYLON2.Space.BONE && upAxis.y == 1 && parentBone) {
parentBone.getRotationMatrixToRef(BABYLON2.Space.WORLD, this.mesh, spaceMat);
} else if (this.upAxisSpace == BABYLON2.Space.LOCAL && upAxis.y == 1 && !parentBone) {
spaceMat.copyFrom(mesh2.getWorldMatrix());
} else {
var forwardAxis = BoneLookController2._tmpVecs[2];
forwardAxis.copyFrom(this._fowardAxis);
if (this._transformYawPitch) {
BABYLON2.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
}
if (parentBone) {
parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
} else {
mesh2.getDirectionToRef(forwardAxis, forwardAxis);
}
var rightAxis = BABYLON2.Vector3.Cross(upAxis, forwardAxis);
rightAxis.normalize();
var forwardAxis = BABYLON2.Vector3.Cross(rightAxis, upAxis);
BABYLON2.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
}
spaceMat.invertToRef(spaceMatInv);
var xzlen = null;
if (checkPitch) {
var localTarget = BoneLookController2._tmpVecs[3];
target.subtractToRef(bonePos, localTarget);
BABYLON2.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
var pitch = Math.atan2(localTarget.y, xzlen);
var newPitch = pitch;
if (pitch > this._maxPitch) {
localTarget.y = this._maxPitchTan * xzlen;
newPitch = this._maxPitch;
} else if (pitch < this._minPitch) {
localTarget.y = this._minPitchTan * xzlen;
newPitch = this._minPitch;
}
if (pitch != newPitch) {
BABYLON2.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
localTarget.addInPlace(bonePos);
target = localTarget;
}
}
if (checkYaw) {
var localTarget = BoneLookController2._tmpVecs[4];
target.subtractToRef(bonePos, localTarget);
BABYLON2.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
var yaw = Math.atan2(localTarget.x, localTarget.z);
var newYaw = yaw;
if (yaw > this._maxYaw || yaw < this._minYaw) {
if (xzlen == null) {
xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
}
if (this._yawRange > Math.PI) {
if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
localTarget.z = this._maxYawCos * xzlen;
localTarget.x = this._maxYawSin * xzlen;
newYaw = this._maxYaw;
} else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
localTarget.z = this._minYawCos * xzlen;
localTarget.x = this._minYawSin * xzlen;
newYaw = this._minYaw;
}
} else {
if (yaw > this._maxYaw) {
localTarget.z = this._maxYawCos * xzlen;
localTarget.x = this._maxYawSin * xzlen;
newYaw = this._maxYaw;
} else if (yaw < this._minYaw) {
localTarget.z = this._minYawCos * xzlen;
localTarget.x = this._minYawSin * xzlen;
newYaw = this._minYaw;
}
}
}
if (this._slerping && this._yawRange > Math.PI) {
var boneFwd = BoneLookController2._tmpVecs[8];
boneFwd.copyFrom(BABYLON2.Axis.Z);
if (this._transformYawPitch) {
BABYLON2.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
}
var boneRotMat = BoneLookController2._tmpMats[4];
this._boneQuat.toRotationMatrix(boneRotMat);
this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
BABYLON2.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
BABYLON2.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
var angBtwTar = this._getAngleBetween(boneYaw, yaw);
var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
if (angBtwTar > angBtwMidYaw) {
if (xzlen == null) {
xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
}
var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
if (angBtwMin < angBtwMax) {
newYaw = boneYaw + Math.PI * 0.75;
localTarget.z = Math.cos(newYaw) * xzlen;
localTarget.x = Math.sin(newYaw) * xzlen;
} else {
newYaw = boneYaw - Math.PI * 0.75;
localTarget.z = Math.cos(newYaw) * xzlen;
localTarget.x = Math.sin(newYaw) * xzlen;
}
}
}
if (yaw != newYaw) {
BABYLON2.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
localTarget.addInPlace(bonePos);
target = localTarget;
}
}
}
var zaxis = BoneLookController2._tmpVecs[5];
var xaxis = BoneLookController2._tmpVecs[6];
var yaxis = BoneLookController2._tmpVecs[7];
var _tmpQuat = BoneLookController2._tmpQuat;
target.subtractToRef(bonePos, zaxis);
zaxis.normalize();
BABYLON2.Vector3.CrossToRef(upAxis, zaxis, xaxis);
xaxis.normalize();
BABYLON2.Vector3.CrossToRef(zaxis, xaxis, yaxis);
yaxis.normalize();
BABYLON2.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
return;
}
if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
return;
}
if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
return;
}
if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
BABYLON2.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
_tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
}
if (this.slerpAmount < 1) {
if (!this._slerping) {
this.bone.getRotationQuaternionToRef(BABYLON2.Space.WORLD, this.mesh, this._boneQuat);
}
if (this._transformYawPitch) {
this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
}
BABYLON2.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
BABYLON2.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
this.bone.setRotationQuaternion(this._boneQuat, BABYLON2.Space.WORLD, this.mesh);
this._slerping = true;
} else {
if (this._transformYawPitch) {
this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
}
this.bone.setRotationMatrix(_tmpMat1, BABYLON2.Space.WORLD, this.mesh);
this._slerping = false;
}
};
BoneLookController2.prototype._getAngleDiff = function(ang1, ang2) {
var angDiff = ang2 - ang1;
angDiff %= Math.PI * 2;
if (angDiff > Math.PI) {
angDiff -= Math.PI * 2;
} else if (angDiff < -Math.PI) {
angDiff += Math.PI * 2;
}
return angDiff;
};
BoneLookController2.prototype._getAngleBetween = function(ang1, ang2) {
ang1 %= 2 * Math.PI;
ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;
ang2 %= 2 * Math.PI;
ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;
var ab = 0;
if (ang1 < ang2) {
ab = ang2 - ang1;
} else {
ab = ang1 - ang2;
}
if (ab > Math.PI) {
ab = Math.PI * 2 - ab;
}
return ab;
};
BoneLookController2.prototype._isAngleBetween = function(ang, ang1, ang2) {
ang %= 2 * Math.PI;
ang = ang < 0 ? ang + 2 * Math.PI : ang;
ang1 %= 2 * Math.PI;
ang1 = ang1 < 0 ? ang1 + 2 * Math.PI : ang1;
ang2 %= 2 * Math.PI;
ang2 = ang2 < 0 ? ang2 + 2 * Math.PI : ang2;
if (ang1 < ang2) {
if (ang > ang1 && ang < ang2) {
return true;
}
} else {
if (ang > ang2 && ang < ang1) {
return true;
}
}
return false;
};
BoneLookController2._tmpVecs = [BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero()];
BoneLookController2._tmpQuat = BABYLON2.Quaternion.Identity();
BoneLookController2._tmpMats = [BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity(), BABYLON2.Matrix.Identity()];
return BoneLookController2;
}()
);
BABYLON2.BoneLookController = BoneLookController;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Skeleton = (
/** @class */
function() {
function Skeleton2(name, id, scene) {
this.name = name;
this.id = id;
this.bones = new Array();
this.needInitialSkinMatrix = false;
this._isDirty = true;
this._meshesWithPoseMatrix = new Array();
this._identity = BABYLON2.Matrix.Identity();
this._ranges = {};
this._lastAbsoluteTransformsUpdateId = -1;
this.doNotSerialize = false;
this._animationPropertiesOverride = null;
this.onBeforeComputeObservable = new BABYLON2.Observable();
this.bones = [];
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
scene.skeletons.push(this);
this._isDirty = true;
}
Object.defineProperty(Skeleton2.prototype, "animationPropertiesOverride", {
/**
* Gets or sets the animation properties override
*/
get: function() {
if (!this._animationPropertiesOverride) {
return this._scene.animationPropertiesOverride;
}
return this._animationPropertiesOverride;
},
set: function(value) {
this._animationPropertiesOverride = value;
},
enumerable: true,
configurable: true
});
Skeleton2.prototype.getTransformMatrices = function(mesh2) {
if (this.needInitialSkinMatrix && mesh2._bonesTransformMatrices) {
return mesh2._bonesTransformMatrices;
}
if (!this._transformMatrices) {
this.prepare();
}
return this._transformMatrices;
};
Skeleton2.prototype.getScene = function() {
return this._scene;
};
Skeleton2.prototype.toString = function(fullDetails) {
var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
if (fullDetails) {
ret += ", Ranges: {";
var first = true;
for (var name_1 in this._ranges) {
if (first) {
ret += ", ";
first = false;
}
ret += name_1;
}
ret += "}";
}
return ret;
};
Skeleton2.prototype.getBoneIndexByName = function(name) {
for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
if (this.bones[boneIndex].name === name) {
return boneIndex;
}
}
return -1;
};
Skeleton2.prototype.createAnimationRange = function(name, from, to) {
if (!this._ranges[name]) {
this._ranges[name] = new BABYLON2.AnimationRange(name, from, to);
for (var i2 = 0, nBones = this.bones.length; i2 < nBones; i2++) {
if (this.bones[i2].animations[0]) {
this.bones[i2].animations[0].createRange(name, from, to);
}
}
}
};
Skeleton2.prototype.deleteAnimationRange = function(name, deleteFrames) {
if (deleteFrames === void 0) {
deleteFrames = true;
}
for (var i2 = 0, nBones = this.bones.length; i2 < nBones; i2++) {
if (this.bones[i2].animations[0]) {
this.bones[i2].animations[0].deleteRange(name, deleteFrames);
}
}
this._ranges[name] = null;
};
Skeleton2.prototype.getAnimationRange = function(name) {
return this._ranges[name];
};
Skeleton2.prototype.getAnimationRanges = function() {
var animationRanges = [];
var name;
var i2 = 0;
for (name in this._ranges) {
animationRanges[i2] = this._ranges[name];
i2++;
}
return animationRanges;
};
Skeleton2.prototype.copyAnimationRange = function(source, name, rescaleAsRequired) {
if (rescaleAsRequired === void 0) {
rescaleAsRequired = false;
}
if (this._ranges[name] || !source.getAnimationRange(name)) {
return false;
}
var ret = true;
var frameOffset = this._getHighestAnimationFrame() + 1;
var boneDict = {};
var sourceBones = source.bones;
var nBones;
var i2;
for (i2 = 0, nBones = sourceBones.length; i2 < nBones; i2++) {
boneDict[sourceBones[i2].name] = sourceBones[i2];
}
if (this.bones.length !== sourceBones.length) {
BABYLON2.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
ret = false;
}
var skelDimensionsRatio = rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
for (i2 = 0, nBones = this.bones.length; i2 < nBones; i2++) {
var boneName = this.bones[i2].name;
var sourceBone = boneDict[boneName];
if (sourceBone) {
ret = ret && this.bones[i2].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
} else {
BABYLON2.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
ret = false;
}
}
var range = source.getAnimationRange(name);
if (range) {
this._ranges[name] = new BABYLON2.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
}
return ret;
};
Skeleton2.prototype.returnToRest = function() {
for (var index = 0; index < this.bones.length; index++) {
this.bones[index].returnToRest();
}
};
Skeleton2.prototype._getHighestAnimationFrame = function() {
var ret = 0;
for (var i2 = 0, nBones = this.bones.length; i2 < nBones; i2++) {
if (this.bones[i2].animations[0]) {
var highest = this.bones[i2].animations[0].getHighestFrame();
if (ret < highest) {
ret = highest;
}
}
}
return ret;
};
Skeleton2.prototype.beginAnimation = function(name, loop, speedRatio, onAnimationEnd) {
var range = this.getAnimationRange(name);
if (!range) {
return null;
}
return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
};
Skeleton2.prototype._markAsDirty = function() {
this._isDirty = true;
};
Skeleton2.prototype._registerMeshWithPoseMatrix = function(mesh2) {
this._meshesWithPoseMatrix.push(mesh2);
};
Skeleton2.prototype._unregisterMeshWithPoseMatrix = function(mesh2) {
var index = this._meshesWithPoseMatrix.indexOf(mesh2);
if (index > -1) {
this._meshesWithPoseMatrix.splice(index, 1);
}
};
Skeleton2.prototype._computeTransformMatrices = function(targetMatrix, initialSkinMatrix) {
this.onBeforeComputeObservable.notifyObservers(this);
for (var index = 0; index < this.bones.length; index++) {
var bone = this.bones[index];
var parentBone = bone.getParent();
if (parentBone) {
bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
} else {
if (initialSkinMatrix) {
bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
} else {
bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
}
}
if (bone._index !== -1) {
var mappedIndex = bone._index === null ? index : bone._index;
bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
}
}
this._identity.copyToArray(targetMatrix, this.bones.length * 16);
};
Skeleton2.prototype.prepare = function() {
if (!this._isDirty) {
return;
}
if (this.needInitialSkinMatrix) {
for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
var mesh2 = this._meshesWithPoseMatrix[index];
var poseMatrix = mesh2.getPoseMatrix();
if (!mesh2._bonesTransformMatrices || mesh2._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
mesh2._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
}
if (this._synchronizedWithMesh !== mesh2) {
this._synchronizedWithMesh = mesh2;
for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
var bone = this.bones[boneIndex];
if (!bone.getParent()) {
var matrix = bone.getBaseMatrix();
matrix.multiplyToRef(poseMatrix, BABYLON2.Tmp.Matrix[1]);
bone._updateDifferenceMatrix(BABYLON2.Tmp.Matrix[1]);
}
}
}
this._computeTransformMatrices(mesh2._bonesTransformMatrices, poseMatrix);
}
} else {
if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
}
this._computeTransformMatrices(this._transformMatrices, null);
}
this._isDirty = false;
this._scene._activeBones.addCount(this.bones.length, false);
};
Skeleton2.prototype.getAnimatables = function() {
if (!this._animatables || this._animatables.length !== this.bones.length) {
this._animatables = [];
for (var index = 0; index < this.bones.length; index++) {
this._animatables.push(this.bones[index]);
}
}
return this._animatables;
};
Skeleton2.prototype.clone = function(name, id) {
var result = new Skeleton2(name, id || name, this._scene);
result.needInitialSkinMatrix = this.needInitialSkinMatrix;
for (var index = 0; index < this.bones.length; index++) {
var source = this.bones[index];
var parentBone = null;
var parent_1 = source.getParent();
if (parent_1) {
var parentIndex = this.bones.indexOf(parent_1);
parentBone = result.bones[parentIndex];
}
var bone = new BABYLON2.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
BABYLON2.Tools.DeepCopy(source.animations, bone.animations);
}
if (this._ranges) {
result._ranges = {};
for (var rangeName in this._ranges) {
var range = this._ranges[rangeName];
if (range) {
result._ranges[rangeName] = range.clone();
}
}
}
this._isDirty = true;
return result;
};
Skeleton2.prototype.enableBlending = function(blendingSpeed) {
if (blendingSpeed === void 0) {
blendingSpeed = 0.01;
}
this.bones.forEach(function(bone) {
bone.animations.forEach(function(animation) {
animation.enableBlending = true;
animation.blendingSpeed = blendingSpeed;
});
});
};
Skeleton2.prototype.dispose = function() {
this._meshesWithPoseMatrix = [];
this.getScene().stopAnimation(this);
this.getScene().removeSkeleton(this);
};
Skeleton2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.id = this.id;
if (this.dimensionsAtRest) {
serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
}
serializationObject.bones = [];
serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
for (var index = 0; index < this.bones.length; index++) {
var bone = this.bones[index];
var parent_2 = bone.getParent();
var serializedBone = {
parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
name: bone.name,
matrix: bone.getBaseMatrix().toArray(),
rest: bone.getRestPose().toArray()
};
serializationObject.bones.push(serializedBone);
if (bone.length) {
serializedBone.length = bone.length;
}
if (bone.metadata) {
serializedBone.metadata = bone.metadata;
}
if (bone.animations && bone.animations.length > 0) {
serializedBone.animation = bone.animations[0].serialize();
}
serializationObject.ranges = [];
for (var name in this._ranges) {
var source = this._ranges[name];
if (!source) {
continue;
}
var range = {};
range.name = name;
range.from = source.from;
range.to = source.to;
serializationObject.ranges.push(range);
}
}
return serializationObject;
};
Skeleton2.Parse = function(parsedSkeleton, scene) {
var skeleton = new Skeleton2(parsedSkeleton.name, parsedSkeleton.id, scene);
if (parsedSkeleton.dimensionsAtRest) {
skeleton.dimensionsAtRest = BABYLON2.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
}
skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
var index;
for (index = 0; index < parsedSkeleton.bones.length; index++) {
var parsedBone = parsedSkeleton.bones[index];
var parentBone = null;
if (parsedBone.parentBoneIndex > -1) {
parentBone = skeleton.bones[parsedBone.parentBoneIndex];
}
var rest = parsedBone.rest ? BABYLON2.Matrix.FromArray(parsedBone.rest) : null;
var bone = new BABYLON2.Bone(parsedBone.name, skeleton, parentBone, BABYLON2.Matrix.FromArray(parsedBone.matrix), rest);
if (parsedBone.id !== void 0 && parsedBone.id !== null) {
bone.id = parsedBone.id;
}
if (parsedBone.length) {
bone.length = parsedBone.length;
}
if (parsedBone.metadata) {
bone.metadata = parsedBone.metadata;
}
if (parsedBone.animation) {
bone.animations.push(BABYLON2.Animation.Parse(parsedBone.animation));
}
}
if (parsedSkeleton.ranges) {
for (index = 0; index < parsedSkeleton.ranges.length; index++) {
var data2 = parsedSkeleton.ranges[index];
skeleton.createAnimationRange(data2.name, data2.from, data2.to);
}
}
return skeleton;
};
Skeleton2.prototype.computeAbsoluteTransforms = function(forceUpdate) {
if (forceUpdate === void 0) {
forceUpdate = false;
}
var renderId = this._scene.getRenderId();
if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
this.bones[0].computeAbsoluteTransforms();
this._lastAbsoluteTransformsUpdateId = renderId;
}
};
Skeleton2.prototype.getPoseMatrix = function() {
var poseMatrix = null;
if (this._meshesWithPoseMatrix.length > 0) {
poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
}
return poseMatrix;
};
Skeleton2.prototype.sortBones = function() {
var bones = new Array();
var visited = new Array(this.bones.length);
for (var index = 0; index < this.bones.length; index++) {
this._sortBones(index, bones, visited);
}
this.bones = bones;
};
Skeleton2.prototype._sortBones = function(index, bones, visited) {
if (visited[index]) {
return;
}
visited[index] = true;
var bone = this.bones[index];
if (bone._index === void 0) {
bone._index = index;
}
var parentBone = bone.getParent();
if (parentBone) {
this._sortBones(this.bones.indexOf(parentBone), bones, visited);
}
bones.push(bone);
};
return Skeleton2;
}()
);
BABYLON2.Skeleton = Skeleton;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var HDRTools = (
/** @class */
function() {
function HDRTools2() {
}
HDRTools2.Ldexp = function(mantissa, exponent) {
if (exponent > 1023) {
return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
}
if (exponent < -1074) {
return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
}
return mantissa * Math.pow(2, exponent);
};
HDRTools2.Rgbe2float = function(float32array, red, green, blue, exponent, index) {
if (exponent > 0) {
exponent = this.Ldexp(1, exponent - (128 + 8));
float32array[index + 0] = red * exponent;
float32array[index + 1] = green * exponent;
float32array[index + 2] = blue * exponent;
} else {
float32array[index + 0] = 0;
float32array[index + 1] = 0;
float32array[index + 2] = 0;
}
};
HDRTools2.readStringLine = function(uint8array, startIndex) {
var line = "";
var character = "";
for (var i2 = startIndex; i2 < uint8array.length - startIndex; i2++) {
character = String.fromCharCode(uint8array[i2]);
if (character == "\n") {
break;
}
line += character;
}
return line;
};
HDRTools2.RGBE_ReadHeader = function(uint8array) {
var height = 0;
var width = 0;
var line = this.readStringLine(uint8array, 0);
if (line[0] != "#" || line[1] != "?") {
throw "Bad HDR Format.";
}
var endOfHeader = false;
var findFormat = false;
var lineIndex = 0;
do {
lineIndex += line.length + 1;
line = this.readStringLine(uint8array, lineIndex);
if (line == "FORMAT=32-bit_rle_rgbe") {
findFormat = true;
} else if (line.length == 0) {
endOfHeader = true;
}
} while (!endOfHeader);
if (!findFormat) {
throw "HDR Bad header format, unsupported FORMAT";
}
lineIndex += line.length + 1;
line = this.readStringLine(uint8array, lineIndex);
var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
var match = sizeRegexp.exec(line);
if (!match || match.length < 3) {
throw "HDR Bad header format, no size";
}
width = parseInt(match[2]);
height = parseInt(match[1]);
if (width < 8 || width > 32767) {
throw "HDR Bad header format, unsupported size";
}
lineIndex += line.length + 1;
return {
height,
width,
dataPosition: lineIndex
};
};
HDRTools2.GetCubeMapTextureData = function(buffer, size) {
var uint8array = new Uint8Array(buffer);
var hdrInfo = this.RGBE_ReadHeader(uint8array);
var data2 = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
var cubeMapData = BABYLON2.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data2, hdrInfo.width, hdrInfo.height, size);
return cubeMapData;
};
HDRTools2.RGBE_ReadPixels = function(uint8array, hdrInfo) {
return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
};
HDRTools2.RGBE_ReadPixels_RLE = function(uint8array, hdrInfo) {
var num_scanlines = hdrInfo.height;
var scanline_width = hdrInfo.width;
var a, b2, c, d, count;
var dataIndex = hdrInfo.dataPosition;
var index = 0, endIndex = 0, i2 = 0;
var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4);
var scanLineArray = new Uint8Array(scanLineArrayBuffer);
var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
var resultArray = new Float32Array(resultBuffer);
while (num_scanlines > 0) {
a = uint8array[dataIndex++];
b2 = uint8array[dataIndex++];
c = uint8array[dataIndex++];
d = uint8array[dataIndex++];
if (a != 2 || b2 != 2 || c & 128) {
throw "HDR Bad header format, not RLE";
}
if ((c << 8 | d) != scanline_width) {
throw "HDR Bad header format, wrong scan line width";
}
index = 0;
for (i2 = 0; i2 < 4; i2++) {
endIndex = (i2 + 1) * scanline_width;
while (index < endIndex) {
a = uint8array[dataIndex++];
b2 = uint8array[dataIndex++];
if (a > 128) {
count = a - 128;
if (count == 0 || count > endIndex - index) {
throw "HDR Bad Format, bad scanline data (run)";
}
while (count-- > 0) {
scanLineArray[index++] = b2;
}
} else {
count = a;
if (count == 0 || count > endIndex - index) {
throw "HDR Bad Format, bad scanline data (non-run)";
}
scanLineArray[index++] = b2;
if (--count > 0) {
for (var j = 0; j < count; j++) {
scanLineArray[index++] = uint8array[dataIndex++];
}
}
}
}
}
for (i2 = 0; i2 < scanline_width; i2++) {
a = scanLineArray[i2];
b2 = scanLineArray[i2 + scanline_width];
c = scanLineArray[i2 + 2 * scanline_width];
d = scanLineArray[i2 + 3 * scanline_width];
this.Rgbe2float(resultArray, a, b2, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i2 * 3);
}
num_scanlines--;
}
return resultArray;
};
return HDRTools2;
}()
);
BABYLON2.HDRTools = HDRTools;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var HDRCubeTexture = (
/** @class */
function(_super) {
__extends(HDRCubeTexture2, _super);
function HDRCubeTexture2(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
if (noMipmap === void 0) {
noMipmap = false;
}
if (generateHarmonics === void 0) {
generateHarmonics = true;
}
if (gammaSpace === void 0) {
gammaSpace = false;
}
if (reserved === void 0) {
reserved = false;
}
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
var _this = _super.call(this, scene) || this;
_this._generateHarmonics = true;
_this._onLoad = null;
_this._onError = null;
_this.coordinatesMode = BABYLON2.Texture.CUBIC_MODE;
_this._isBlocking = true;
_this._rotationY = 0;
_this.boundingBoxPosition = BABYLON2.Vector3.Zero();
if (!url) {
return _this;
}
_this.name = url;
_this.url = url;
_this.hasAlpha = false;
_this.isCube = true;
_this._textureMatrix = BABYLON2.Matrix.Identity();
_this._onLoad = onLoad;
_this._onError = onError;
_this.gammaSpace = gammaSpace;
_this._noMipmap = noMipmap;
_this._size = size;
_this._texture = _this._getFromCache(url, _this._noMipmap);
if (!_this._texture) {
if (!scene.useDelayedTextureLoading) {
_this.loadTexture();
} else {
_this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED;
}
}
return _this;
}
Object.defineProperty(HDRCubeTexture2.prototype, "isBlocking", {
/**
* Gets wether or not the texture is blocking during loading.
*/
get: function() {
return this._isBlocking;
},
/**
* Sets wether or not the texture is blocking during loading.
*/
set: function(value) {
this._isBlocking = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HDRCubeTexture2.prototype, "rotationY", {
/**
* Gets texture matrix rotation angle around Y axis radians.
*/
get: function() {
return this._rotationY;
},
/**
* Sets texture matrix rotation angle around Y axis in radians.
*/
set: function(value) {
this._rotationY = value;
this.setReflectionTextureMatrix(BABYLON2.Matrix.RotationY(this._rotationY));
},
enumerable: true,
configurable: true
});
Object.defineProperty(HDRCubeTexture2.prototype, "boundingBoxSize", {
get: function() {
return this._boundingBoxSize;
},
/**
* Gets or sets the size of the bounding box associated with the cube texture
* When defined, the cubemap will switch to local mode
* @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
* @example https://www.babylonjs-playground.com/#RNASML
*/
set: function(value) {
if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
return;
}
this._boundingBoxSize = value;
var scene = this.getScene();
if (scene) {
scene.markAllMaterialsAsDirty(BABYLON2.Material.TextureDirtyFlag);
}
},
enumerable: true,
configurable: true
});
HDRCubeTexture2.prototype.loadTexture = function() {
var _this = this;
var callback = function(buffer) {
_this.lodGenerationOffset = 0;
_this.lodGenerationScale = 0.8;
var scene2 = _this.getScene();
if (!scene2) {
return null;
}
var data2 = BABYLON2.HDRTools.GetCubeMapTextureData(buffer, _this._size);
if (_this._generateHarmonics) {
var sphericalPolynomial = BABYLON2.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data2);
_this.sphericalPolynomial = sphericalPolynomial;
}
var results = [];
var byteArray = null;
for (var j = 0; j < 6; j++) {
if (!scene2.getEngine().getCaps().textureFloat) {
var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
byteArray = new Uint8Array(byteBuffer);
}
var dataFace = data2[HDRCubeTexture2._facesMapping[j]];
if (_this.gammaSpace || byteArray) {
for (var i2 = 0; i2 < _this._size * _this._size; i2++) {
if (_this.gammaSpace) {
dataFace[i2 * 3 + 0] = Math.pow(dataFace[i2 * 3 + 0], BABYLON2.ToGammaSpace);
dataFace[i2 * 3 + 1] = Math.pow(dataFace[i2 * 3 + 1], BABYLON2.ToGammaSpace);
dataFace[i2 * 3 + 2] = Math.pow(dataFace[i2 * 3 + 2], BABYLON2.ToGammaSpace);
}
if (byteArray) {
var r = Math.max(dataFace[i2 * 3 + 0] * 255, 0);
var g = Math.max(dataFace[i2 * 3 + 1] * 255, 0);
var b2 = Math.max(dataFace[i2 * 3 + 2] * 255, 0);
var max = Math.max(Math.max(r, g), b2);
if (max > 255) {
var scale = 255 / max;
r *= scale;
g *= scale;
b2 *= scale;
}
byteArray[i2 * 3 + 0] = r;
byteArray[i2 * 3 + 1] = g;
byteArray[i2 * 3 + 2] = b2;
}
}
}
if (byteArray) {
results.push(byteArray);
} else {
results.push(dataFace);
}
}
return results;
};
var scene = this.getScene();
if (scene) {
this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON2.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON2.Engine.TEXTURETYPE_FLOAT : BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
}
};
HDRCubeTexture2.prototype.clone = function() {
var scene = this.getScene();
if (!scene) {
return this;
}
var newTexture = new HDRCubeTexture2(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
newTexture.level = this.level;
newTexture.wrapU = this.wrapU;
newTexture.wrapV = this.wrapV;
newTexture.coordinatesIndex = this.coordinatesIndex;
newTexture.coordinatesMode = this.coordinatesMode;
return newTexture;
};
HDRCubeTexture2.prototype.delayLoad = function() {
if (this.delayLoadState !== BABYLON2.Engine.DELAYLOADSTATE_NOTLOADED) {
return;
}
this.delayLoadState = BABYLON2.Engine.DELAYLOADSTATE_LOADED;
this._texture = this._getFromCache(this.url, this._noMipmap);
if (!this._texture) {
this.loadTexture();
}
};
HDRCubeTexture2.prototype.getReflectionTextureMatrix = function() {
return this._textureMatrix;
};
HDRCubeTexture2.prototype.setReflectionTextureMatrix = function(value) {
this._textureMatrix = value;
};
HDRCubeTexture2.Parse = function(parsedTexture, scene, rootUrl) {
var texture = null;
if (parsedTexture.name && !parsedTexture.isRenderTarget) {
texture = new HDRCubeTexture2(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
texture.name = parsedTexture.name;
texture.hasAlpha = parsedTexture.hasAlpha;
texture.level = parsedTexture.level;
texture.coordinatesMode = parsedTexture.coordinatesMode;
texture.isBlocking = parsedTexture.isBlocking;
}
if (texture) {
if (parsedTexture.boundingBoxPosition) {
texture.boundingBoxPosition = BABYLON2.Vector3.FromArray(parsedTexture.boundingBoxPosition);
}
if (parsedTexture.boundingBoxSize) {
texture.boundingBoxSize = BABYLON2.Vector3.FromArray(parsedTexture.boundingBoxSize);
}
if (parsedTexture.rotationY) {
texture.rotationY = parsedTexture.rotationY;
}
}
return texture;
};
HDRCubeTexture2.prototype.serialize = function() {
if (!this.name) {
return null;
}
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.hasAlpha = this.hasAlpha;
serializationObject.isCube = true;
serializationObject.level = this.level;
serializationObject.size = this._size;
serializationObject.coordinatesMode = this.coordinatesMode;
serializationObject.useInGammaSpace = this.gammaSpace;
serializationObject.generateHarmonics = this._generateHarmonics;
serializationObject.customType = "BABYLON.HDRCubeTexture";
serializationObject.noMipmap = this._noMipmap;
serializationObject.isBlocking = this._isBlocking;
serializationObject.rotationY = this._rotationY;
return serializationObject;
};
HDRCubeTexture2._facesMapping = [
"right",
"left",
"up",
"down",
"front",
"back"
];
return HDRCubeTexture2;
}(BABYLON2.BaseTexture)
);
BABYLON2.HDRCubeTexture = HDRCubeTexture;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PanoramaToCubeMapTools = (
/** @class */
function() {
function PanoramaToCubeMapTools2() {
}
PanoramaToCubeMapTools2.ConvertPanoramaToCubemap = function(float32Array, inputWidth, inputHeight, size) {
if (!float32Array) {
throw "ConvertPanoramaToCubemap: input cannot be null";
}
if (float32Array.length != inputWidth * inputHeight * 3) {
throw "ConvertPanoramaToCubemap: input size is wrong";
}
var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
return {
front: textureFront,
back: textureBack,
left: textureLeft,
right: textureRight,
up: textureUp,
down: textureDown,
size,
type: BABYLON2.Engine.TEXTURETYPE_FLOAT,
format: BABYLON2.Engine.TEXTUREFORMAT_RGB,
gammaSpace: false
};
};
PanoramaToCubeMapTools2.CreateCubemapTexture = function(texSize, faceData, float32Array, inputWidth, inputHeight) {
var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
var textureArray = new Float32Array(buffer);
var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
var dy = 1 / texSize;
var fy = 0;
for (var y = 0; y < texSize; y++) {
var xv1 = faceData[0];
var xv2 = faceData[2];
for (var x = 0; x < texSize; x++) {
var v = xv2.subtract(xv1).scale(fy).add(xv1);
v.normalize();
var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
textureArray[y * texSize * 3 + x * 3 + 0] = color.r;
textureArray[y * texSize * 3 + x * 3 + 1] = color.g;
textureArray[y * texSize * 3 + x * 3 + 2] = color.b;
xv1 = xv1.add(rotDX1);
xv2 = xv2.add(rotDX2);
}
fy += dy;
}
return textureArray;
};
PanoramaToCubeMapTools2.CalcProjectionSpherical = function(vDir, float32Array, inputWidth, inputHeight) {
var theta = Math.atan2(vDir.z, vDir.x);
var phi = Math.acos(vDir.y);
while (theta < -Math.PI) {
theta += 2 * Math.PI;
}
while (theta > Math.PI) {
theta -= 2 * Math.PI;
}
var dx = theta / Math.PI;
var dy = phi / Math.PI;
dx = dx * 0.5 + 0.5;
var px = Math.round(dx * inputWidth);
if (px < 0) {
px = 0;
} else if (px >= inputWidth) {
px = inputWidth - 1;
}
var py = Math.round(dy * inputHeight);
if (py < 0) {
py = 0;
} else if (py >= inputHeight) {
py = inputHeight - 1;
}
var inputY = inputHeight - py - 1;
var r = float32Array[inputY * inputWidth * 3 + px * 3 + 0];
var g = float32Array[inputY * inputWidth * 3 + px * 3 + 1];
var b2 = float32Array[inputY * inputWidth * 3 + px * 3 + 2];
return {
r,
g,
b: b2
};
};
PanoramaToCubeMapTools2.FACE_FRONT = [
new BABYLON2.Vector3(-1, -1, -1),
new BABYLON2.Vector3(1, -1, -1),
new BABYLON2.Vector3(-1, 1, -1),
new BABYLON2.Vector3(1, 1, -1)
];
PanoramaToCubeMapTools2.FACE_BACK = [
new BABYLON2.Vector3(1, -1, 1),
new BABYLON2.Vector3(-1, -1, 1),
new BABYLON2.Vector3(1, 1, 1),
new BABYLON2.Vector3(-1, 1, 1)
];
PanoramaToCubeMapTools2.FACE_RIGHT = [
new BABYLON2.Vector3(1, -1, -1),
new BABYLON2.Vector3(1, -1, 1),
new BABYLON2.Vector3(1, 1, -1),
new BABYLON2.Vector3(1, 1, 1)
];
PanoramaToCubeMapTools2.FACE_LEFT = [
new BABYLON2.Vector3(-1, -1, 1),
new BABYLON2.Vector3(-1, -1, -1),
new BABYLON2.Vector3(-1, 1, 1),
new BABYLON2.Vector3(-1, 1, -1)
];
PanoramaToCubeMapTools2.FACE_DOWN = [
new BABYLON2.Vector3(-1, 1, -1),
new BABYLON2.Vector3(1, 1, -1),
new BABYLON2.Vector3(-1, 1, 1),
new BABYLON2.Vector3(1, 1, 1)
];
PanoramaToCubeMapTools2.FACE_UP = [
new BABYLON2.Vector3(-1, -1, 1),
new BABYLON2.Vector3(1, -1, 1),
new BABYLON2.Vector3(-1, -1, -1),
new BABYLON2.Vector3(1, -1, -1)
];
return PanoramaToCubeMapTools2;
}()
);
BABYLON2.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var IndexedVector2 = (
/** @class */
function(_super) {
__extends(IndexedVector22, _super);
function IndexedVector22(original, index) {
var _this = _super.call(this, original.x, original.y) || this;
_this.index = index;
return _this;
}
return IndexedVector22;
}(BABYLON2.Vector2)
);
var PolygonPoints = (
/** @class */
function() {
function PolygonPoints2() {
this.elements = new Array();
}
PolygonPoints2.prototype.add = function(originalPoints) {
var _this = this;
var result = new Array();
originalPoints.forEach(function(point) {
if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
var newPoint = new IndexedVector2(point, _this.elements.length);
result.push(newPoint);
_this.elements.push(newPoint);
}
});
return result;
};
PolygonPoints2.prototype.computeBounds = function() {
var lmin = new BABYLON2.Vector2(this.elements[0].x, this.elements[0].y);
var lmax = new BABYLON2.Vector2(this.elements[0].x, this.elements[0].y);
this.elements.forEach(function(point) {
if (point.x < lmin.x) {
lmin.x = point.x;
} else if (point.x > lmax.x) {
lmax.x = point.x;
}
if (point.y < lmin.y) {
lmin.y = point.y;
} else if (point.y > lmax.y) {
lmax.y = point.y;
}
});
return {
min: lmin,
max: lmax,
width: lmax.x - lmin.x,
height: lmax.y - lmin.y
};
};
return PolygonPoints2;
}()
);
var Polygon = (
/** @class */
function() {
function Polygon2() {
}
Polygon2.Rectangle = function(xmin, ymin, xmax, ymax) {
return [
new BABYLON2.Vector2(xmin, ymin),
new BABYLON2.Vector2(xmax, ymin),
new BABYLON2.Vector2(xmax, ymax),
new BABYLON2.Vector2(xmin, ymax)
];
};
Polygon2.Circle = function(radius, cx, cy, numberOfSides) {
if (cx === void 0) {
cx = 0;
}
if (cy === void 0) {
cy = 0;
}
if (numberOfSides === void 0) {
numberOfSides = 32;
}
var result = new Array();
var angle = 0;
var increment = Math.PI * 2 / numberOfSides;
for (var i2 = 0; i2 < numberOfSides; i2++) {
result.push(new BABYLON2.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
angle -= increment;
}
return result;
};
Polygon2.Parse = function(input) {
var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function(val) {
return !isNaN(val);
});
var i2, result = [];
for (i2 = 0; i2 < (floats.length & 2147483646); i2 += 2) {
result.push(new BABYLON2.Vector2(floats[i2], floats[i2 + 1]));
}
return result;
};
Polygon2.StartingAt = function(x, y) {
return BABYLON2.Path2.StartingAt(x, y);
};
return Polygon2;
}()
);
BABYLON2.Polygon = Polygon;
var PolygonMeshBuilder = (
/** @class */
function() {
function PolygonMeshBuilder2(name, contours, scene) {
this._points = new PolygonPoints();
this._outlinepoints = new PolygonPoints();
this._holes = new Array();
this._epoints = new Array();
this._eholes = new Array();
this._name = name;
this._scene = scene;
var points;
if (contours instanceof BABYLON2.Path2) {
points = contours.getPoints();
} else {
points = contours;
}
this._addToepoint(points);
this._points.add(points);
this._outlinepoints.add(points);
if (typeof earcut === "undefined") {
BABYLON2.Tools.Warn("Earcut was not found, the polygon will not be built.");
}
}
PolygonMeshBuilder2.prototype._addToepoint = function(points) {
for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
var p = points_1[_i];
this._epoints.push(p.x, p.y);
}
};
PolygonMeshBuilder2.prototype.addHole = function(hole) {
this._points.add(hole);
var holepoints = new PolygonPoints();
holepoints.add(hole);
this._holes.push(holepoints);
this._eholes.push(this._epoints.length / 2);
this._addToepoint(hole);
return this;
};
PolygonMeshBuilder2.prototype.build = function(updatable, depth) {
var _this = this;
if (updatable === void 0) {
updatable = false;
}
if (depth === void 0) {
depth = 0;
}
var result = new BABYLON2.Mesh(this._name, this._scene);
var normals = new Array();
var positions = new Array();
var uvs = new Array();
var bounds = this._points.computeBounds();
this._points.elements.forEach(function(p) {
normals.push(0, 1, 0);
positions.push(p.x, 0, p.y);
uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
});
var indices = new Array();
var res = earcut(this._epoints, this._eholes, 2);
for (var i2 = 0; i2 < res.length; i2++) {
indices.push(res[i2]);
}
if (depth > 0) {
var positionscount = positions.length / 3;
this._points.elements.forEach(function(p) {
normals.push(0, -1, 0);
positions.push(p.x, -depth, p.y);
uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
});
var totalCount = indices.length;
for (var i2 = 0; i2 < totalCount; i2 += 3) {
var i0 = indices[i2 + 0];
var i1 = indices[i2 + 1];
var i22 = indices[i2 + 2];
indices.push(i22 + positionscount);
indices.push(i1 + positionscount);
indices.push(i0 + positionscount);
}
this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
this._holes.forEach(function(hole) {
_this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
});
}
result.setVerticesData(BABYLON2.VertexBuffer.PositionKind, positions, updatable);
result.setVerticesData(BABYLON2.VertexBuffer.NormalKind, normals, updatable);
result.setVerticesData(BABYLON2.VertexBuffer.UVKind, uvs, updatable);
result.setIndices(indices);
return result;
};
PolygonMeshBuilder2.prototype.addSide = function(positions, normals, uvs, indices, bounds, points, depth, flip) {
var StartIndex = positions.length / 3;
var ulength = 0;
for (var i2 = 0; i2 < points.elements.length; i2++) {
var p = points.elements[i2];
var p1;
if (i2 + 1 > points.elements.length - 1) {
p1 = points.elements[0];
} else {
p1 = points.elements[i2 + 1];
}
positions.push(p.x, 0, p.y);
positions.push(p.x, -depth, p.y);
positions.push(p1.x, 0, p1.y);
positions.push(p1.x, -depth, p1.y);
var v1 = new BABYLON2.Vector3(p.x, 0, p.y);
var v2 = new BABYLON2.Vector3(p1.x, 0, p1.y);
var v3 = v2.subtract(v1);
var v4 = new BABYLON2.Vector3(0, 1, 0);
var vn = BABYLON2.Vector3.Cross(v3, v4);
vn = vn.normalize();
uvs.push(ulength / bounds.width, 0);
uvs.push(ulength / bounds.width, 1);
ulength += v3.length();
uvs.push(ulength / bounds.width, 0);
uvs.push(ulength / bounds.width, 1);
if (!flip) {
normals.push(-vn.x, -vn.y, -vn.z);
normals.push(-vn.x, -vn.y, -vn.z);
normals.push(-vn.x, -vn.y, -vn.z);
normals.push(-vn.x, -vn.y, -vn.z);
indices.push(StartIndex);
indices.push(StartIndex + 1);
indices.push(StartIndex + 2);
indices.push(StartIndex + 1);
indices.push(StartIndex + 3);
indices.push(StartIndex + 2);
} else {
normals.push(vn.x, vn.y, vn.z);
normals.push(vn.x, vn.y, vn.z);
normals.push(vn.x, vn.y, vn.z);
normals.push(vn.x, vn.y, vn.z);
indices.push(StartIndex);
indices.push(StartIndex + 2);
indices.push(StartIndex + 1);
indices.push(StartIndex + 1);
indices.push(StartIndex + 2);
indices.push(StartIndex + 3);
}
StartIndex += 4;
}
};
return PolygonMeshBuilder2;
}()
);
BABYLON2.PolygonMeshBuilder = PolygonMeshBuilder;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var currentCSGMeshId = 0;
var Vertex = (
/** @class */
function() {
function Vertex2(pos, normal, uv) {
this.pos = pos;
this.normal = normal;
this.uv = uv;
}
Vertex2.prototype.clone = function() {
return new Vertex2(this.pos.clone(), this.normal.clone(), this.uv.clone());
};
Vertex2.prototype.flip = function() {
this.normal = this.normal.scale(-1);
};
Vertex2.prototype.interpolate = function(other, t) {
return new Vertex2(BABYLON2.Vector3.Lerp(this.pos, other.pos, t), BABYLON2.Vector3.Lerp(this.normal, other.normal, t), BABYLON2.Vector2.Lerp(this.uv, other.uv, t));
};
return Vertex2;
}()
);
var Plane = (
/** @class */
function() {
function Plane2(normal, w) {
this.normal = normal;
this.w = w;
}
Plane2.FromPoints = function(a, b2, c) {
var v0 = c.subtract(a);
var v1 = b2.subtract(a);
if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
return null;
}
var n = BABYLON2.Vector3.Normalize(BABYLON2.Vector3.Cross(v0, v1));
return new Plane2(n, BABYLON2.Vector3.Dot(n, a));
};
Plane2.prototype.clone = function() {
return new Plane2(this.normal.clone(), this.w);
};
Plane2.prototype.flip = function() {
this.normal.scaleInPlace(-1);
this.w = -this.w;
};
Plane2.prototype.splitPolygon = function(polygon, coplanarFront, coplanarBack, front, back) {
var COPLANAR = 0;
var FRONT = 1;
var BACK = 2;
var SPANNING = 3;
var polygonType = 0;
var types = [];
var i2;
var t;
for (i2 = 0; i2 < polygon.vertices.length; i2++) {
t = BABYLON2.Vector3.Dot(this.normal, polygon.vertices[i2].pos) - this.w;
var type = t < -Plane2.EPSILON ? BACK : t > Plane2.EPSILON ? FRONT : COPLANAR;
polygonType |= type;
types.push(type);
}
switch (polygonType) {
case COPLANAR:
(BABYLON2.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
break;
case FRONT:
front.push(polygon);
break;
case BACK:
back.push(polygon);
break;
case SPANNING:
var f = [], b2 = [];
for (i2 = 0; i2 < polygon.vertices.length; i2++) {
var j = (i2 + 1) % polygon.vertices.length;
var ti = types[i2], tj = types[j];
var vi = polygon.vertices[i2], vj = polygon.vertices[j];
if (ti !== BACK) {
f.push(vi);
}
if (ti !== FRONT) {
b2.push(ti !== BACK ? vi.clone() : vi);
}
if ((ti | tj) === SPANNING) {
t = (this.w - BABYLON2.Vector3.Dot(this.normal, vi.pos)) / BABYLON2.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
var v = vi.interpolate(vj, t);
f.push(v);
b2.push(v.clone());
}
}
var poly;
if (f.length >= 3) {
poly = new Polygon(f, polygon.shared);
if (poly.plane) {
front.push(poly);
}
}
if (b2.length >= 3) {
poly = new Polygon(b2, polygon.shared);
if (poly.plane) {
back.push(poly);
}
}
break;
}
};
Plane2.EPSILON = 1e-5;
return Plane2;
}()
);
var Polygon = (
/** @class */
function() {
function Polygon2(vertices, shared) {
this.vertices = vertices;
this.shared = shared;
this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
}
Polygon2.prototype.clone = function() {
var vertices = this.vertices.map(function(v) {
return v.clone();
});
return new Polygon2(vertices, this.shared);
};
Polygon2.prototype.flip = function() {
this.vertices.reverse().map(function(v) {
v.flip();
});
this.plane.flip();
};
return Polygon2;
}()
);
var Node = (
/** @class */
function() {
function Node2(polygons) {
this.plane = null;
this.front = null;
this.back = null;
this.polygons = new Array();
if (polygons) {
this.build(polygons);
}
}
Node2.prototype.clone = function() {
var node = new Node2();
node.plane = this.plane && this.plane.clone();
node.front = this.front && this.front.clone();
node.back = this.back && this.back.clone();
node.polygons = this.polygons.map(function(p) {
return p.clone();
});
return node;
};
Node2.prototype.invert = function() {
for (var i2 = 0; i2 < this.polygons.length; i2++) {
this.polygons[i2].flip();
}
if (this.plane) {
this.plane.flip();
}
if (this.front) {
this.front.invert();
}
if (this.back) {
this.back.invert();
}
var temp = this.front;
this.front = this.back;
this.back = temp;
};
Node2.prototype.clipPolygons = function(polygons) {
if (!this.plane) {
return polygons.slice();
}
var front = new Array(), back = new Array();
for (var i2 = 0; i2 < polygons.length; i2++) {
this.plane.splitPolygon(polygons[i2], front, back, front, back);
}
if (this.front) {
front = this.front.clipPolygons(front);
}
if (this.back) {
back = this.back.clipPolygons(back);
} else {
back = [];
}
return front.concat(back);
};
Node2.prototype.clipTo = function(bsp) {
this.polygons = bsp.clipPolygons(this.polygons);
if (this.front) {
this.front.clipTo(bsp);
}
if (this.back) {
this.back.clipTo(bsp);
}
};
Node2.prototype.allPolygons = function() {
var polygons = this.polygons.slice();
if (this.front) {
polygons = polygons.concat(this.front.allPolygons());
}
if (this.back) {
polygons = polygons.concat(this.back.allPolygons());
}
return polygons;
};
Node2.prototype.build = function(polygons) {
if (!polygons.length) {
return;
}
if (!this.plane) {
this.plane = polygons[0].plane.clone();
}
var front = new Array(), back = new Array();
for (var i2 = 0; i2 < polygons.length; i2++) {
this.plane.splitPolygon(polygons[i2], this.polygons, this.polygons, front, back);
}
if (front.length) {
if (!this.front) {
this.front = new Node2();
}
this.front.build(front);
}
if (back.length) {
if (!this.back) {
this.back = new Node2();
}
this.back.build(back);
}
};
return Node2;
}()
);
var CSG = (
/** @class */
function() {
function CSG2() {
this.polygons = new Array();
}
CSG2.FromMesh = function(mesh2) {
var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
if (mesh2 instanceof BABYLON2.Mesh) {
mesh2.computeWorldMatrix(true);
matrix = mesh2.getWorldMatrix();
meshPosition = mesh2.position.clone();
meshRotation = mesh2.rotation.clone();
if (mesh2.rotationQuaternion) {
meshRotationQuaternion = mesh2.rotationQuaternion.clone();
}
meshScaling = mesh2.scaling.clone();
} else {
throw "BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh";
}
var indices = mesh2.getIndices(), positions = mesh2.getVerticesData(BABYLON2.VertexBuffer.PositionKind), normals = mesh2.getVerticesData(BABYLON2.VertexBuffer.NormalKind), uvs = mesh2.getVerticesData(BABYLON2.VertexBuffer.UVKind);
var subMeshes = mesh2.subMeshes;
for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
for (var i2 = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i2 < il; i2 += 3) {
vertices = [];
for (var j = 0; j < 3; j++) {
var sourceNormal = new BABYLON2.Vector3(normals[indices[i2 + j] * 3], normals[indices[i2 + j] * 3 + 1], normals[indices[i2 + j] * 3 + 2]);
uv = new BABYLON2.Vector2(uvs[indices[i2 + j] * 2], uvs[indices[i2 + j] * 2 + 1]);
var sourcePosition = new BABYLON2.Vector3(positions[indices[i2 + j] * 3], positions[indices[i2 + j] * 3 + 1], positions[indices[i2 + j] * 3 + 2]);
position = BABYLON2.Vector3.TransformCoordinates(sourcePosition, matrix);
normal = BABYLON2.Vector3.TransformNormal(sourceNormal, matrix);
vertex = new Vertex(position, normal, uv);
vertices.push(vertex);
}
polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
if (polygon.plane) {
polygons.push(polygon);
}
}
}
var csg = CSG2.FromPolygons(polygons);
csg.matrix = matrix;
csg.position = meshPosition;
csg.rotation = meshRotation;
csg.scaling = meshScaling;
csg.rotationQuaternion = meshRotationQuaternion;
currentCSGMeshId++;
return csg;
};
CSG2.FromPolygons = function(polygons) {
var csg = new CSG2();
csg.polygons = polygons;
return csg;
};
CSG2.prototype.clone = function() {
var csg = new CSG2();
csg.polygons = this.polygons.map(function(p) {
return p.clone();
});
csg.copyTransformAttributes(this);
return csg;
};
CSG2.prototype.union = function(csg) {
var a = new Node(this.clone().polygons);
var b2 = new Node(csg.clone().polygons);
a.clipTo(b2);
b2.clipTo(a);
b2.invert();
b2.clipTo(a);
b2.invert();
a.build(b2.allPolygons());
return CSG2.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
};
CSG2.prototype.unionInPlace = function(csg) {
var a = new Node(this.polygons);
var b2 = new Node(csg.polygons);
a.clipTo(b2);
b2.clipTo(a);
b2.invert();
b2.clipTo(a);
b2.invert();
a.build(b2.allPolygons());
this.polygons = a.allPolygons();
};
CSG2.prototype.subtract = function(csg) {
var a = new Node(this.clone().polygons);
var b2 = new Node(csg.clone().polygons);
a.invert();
a.clipTo(b2);
b2.clipTo(a);
b2.invert();
b2.clipTo(a);
b2.invert();
a.build(b2.allPolygons());
a.invert();
return CSG2.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
};
CSG2.prototype.subtractInPlace = function(csg) {
var a = new Node(this.polygons);
var b2 = new Node(csg.polygons);
a.invert();
a.clipTo(b2);
b2.clipTo(a);
b2.invert();
b2.clipTo(a);
b2.invert();
a.build(b2.allPolygons());
a.invert();
this.polygons = a.allPolygons();
};
CSG2.prototype.intersect = function(csg) {
var a = new Node(this.clone().polygons);
var b2 = new Node(csg.clone().polygons);
a.invert();
b2.clipTo(a);
b2.invert();
a.clipTo(b2);
b2.clipTo(a);
a.build(b2.allPolygons());
a.invert();
return CSG2.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
};
CSG2.prototype.intersectInPlace = function(csg) {
var a = new Node(this.polygons);
var b2 = new Node(csg.polygons);
a.invert();
b2.clipTo(a);
b2.invert();
a.clipTo(b2);
b2.clipTo(a);
a.build(b2.allPolygons());
a.invert();
this.polygons = a.allPolygons();
};
CSG2.prototype.inverse = function() {
var csg = this.clone();
csg.inverseInPlace();
return csg;
};
CSG2.prototype.inverseInPlace = function() {
this.polygons.map(function(p) {
p.flip();
});
};
CSG2.prototype.copyTransformAttributes = function(csg) {
this.matrix = csg.matrix;
this.position = csg.position;
this.rotation = csg.rotation;
this.scaling = csg.scaling;
this.rotationQuaternion = csg.rotationQuaternion;
return this;
};
CSG2.prototype.buildMeshGeometry = function(name, scene, keepSubMeshes) {
var matrix = this.matrix.clone();
matrix.invert();
var mesh2 = new BABYLON2.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON2.Vector3.Zero(), normal = BABYLON2.Vector3.Zero(), uv = BABYLON2.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
if (keepSubMeshes) {
polygons.sort(function(a, b2) {
if (a.shared.meshId === b2.shared.meshId) {
return a.shared.subMeshId - b2.shared.subMeshId;
} else {
return a.shared.meshId - b2.shared.meshId;
}
});
}
for (var i2 = 0, il = polygons.length; i2 < il; i2++) {
polygon = polygons[i2];
if (!subMesh_dict[polygon.shared.meshId]) {
subMesh_dict[polygon.shared.meshId] = {};
}
if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
indexStart: Infinity,
indexEnd: -Infinity,
materialIndex: polygon.shared.materialIndex
};
}
subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
polygonIndices[0] = 0;
polygonIndices[1] = j - 1;
polygonIndices[2] = j;
for (var k = 0; k < 3; k++) {
vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
var localVertex = BABYLON2.Vector3.TransformCoordinates(vertex, matrix);
var localNormal = BABYLON2.Vector3.TransformNormal(normal, matrix);
vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z];
if (!(typeof vertex_idx !== "undefined" && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
vertices.push(localVertex.x, localVertex.y, localVertex.z);
uvs.push(uv.x, uv.y);
normals.push(normal.x, normal.y, normal.z);
vertex_idx = vertice_dict[localVertex.x + "," + localVertex.y + "," + localVertex.z] = vertices.length / 3 - 1;
}
indices.push(vertex_idx);
subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
currentIndex++;
}
}
}
mesh2.setVerticesData(BABYLON2.VertexBuffer.PositionKind, vertices);
mesh2.setVerticesData(BABYLON2.VertexBuffer.NormalKind, normals);
mesh2.setVerticesData(BABYLON2.VertexBuffer.UVKind, uvs);
mesh2.setIndices(indices, null);
if (keepSubMeshes) {
var materialIndexOffset = 0, materialMaxIndex;
mesh2.subMeshes = new Array();
for (var m in subMesh_dict) {
materialMaxIndex = -1;
for (var sm in subMesh_dict[m]) {
subMesh_obj = subMesh_dict[m][sm];
BABYLON2.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh2);
materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
}
materialIndexOffset += ++materialMaxIndex;
}
}
return mesh2;
};
CSG2.prototype.toMesh = function(name, material, scene, keepSubMeshes) {
var mesh2 = this.buildMeshGeometry(name, scene, keepSubMeshes);
mesh2.material = material;
mesh2.position.copyFrom(this.position);
mesh2.rotation.copyFrom(this.rotation);
if (this.rotationQuaternion) {
mesh2.rotationQuaternion = this.rotationQuaternion.clone();
}
mesh2.scaling.copyFrom(this.scaling);
mesh2.computeWorldMatrix(true);
return mesh2;
};
return CSG2;
}()
);
BABYLON2.CSG = CSG;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var LensFlare = (
/** @class */
function() {
function LensFlare2(size, position, color, imgUrl, system) {
this.size = size;
this.position = position;
this.alphaMode = BABYLON2.Engine.ALPHA_ONEONE;
this.color = color || new BABYLON2.Color3(1, 1, 1);
this.texture = imgUrl ? new BABYLON2.Texture(imgUrl, system.getScene(), true) : null;
this._system = system;
system.lensFlares.push(this);
}
LensFlare2.AddFlare = function(size, position, color, imgUrl, system) {
return new LensFlare2(size, position, color, imgUrl, system);
};
LensFlare2.prototype.dispose = function() {
if (this.texture) {
this.texture.dispose();
}
var index = this._system.lensFlares.indexOf(this);
this._system.lensFlares.splice(index, 1);
};
return LensFlare2;
}()
);
BABYLON2.LensFlare = LensFlare;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractScene.AddParser(BABYLON2.SceneComponentConstants.NAME_LENSFLARESYSTEM, function(parsedData, scene, container, rootUrl) {
if (parsedData.lensFlareSystems !== void 0 && parsedData.lensFlareSystems !== null) {
if (!container.lensFlareSystems) {
container.lensFlareSystems = new Array();
}
for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
var lf = BABYLON2.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
container.lensFlareSystems.push(lf);
}
}
});
BABYLON2.AbstractScene.prototype.getLensFlareSystemByName = function(name) {
for (var index = 0; index < this.lensFlareSystems.length; index++) {
if (this.lensFlareSystems[index].name === name) {
return this.lensFlareSystems[index];
}
}
return null;
};
BABYLON2.AbstractScene.prototype.getLensFlareSystemByID = function(id) {
for (var index = 0; index < this.lensFlareSystems.length; index++) {
if (this.lensFlareSystems[index].id === id) {
return this.lensFlareSystems[index];
}
}
return null;
};
BABYLON2.AbstractScene.prototype.removeLensFlareSystem = function(toRemove) {
var index = this.lensFlareSystems.indexOf(toRemove);
if (index !== -1) {
this.lensFlareSystems.splice(index, 1);
}
return index;
};
BABYLON2.AbstractScene.prototype.addLensFlareSystem = function(newLensFlareSystem) {
this.lensFlareSystems.push(newLensFlareSystem);
};
var LensFlareSystemSceneComponent = (
/** @class */
function() {
function LensFlareSystemSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_LENSFLARESYSTEM;
this.scene = scene;
scene.lensFlareSystems = new Array();
}
LensFlareSystemSceneComponent2.prototype.register = function() {
this.scene._afterCameraDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
};
LensFlareSystemSceneComponent2.prototype.rebuild = function() {
};
LensFlareSystemSceneComponent2.prototype.addFromContainer = function(container) {
var _this = this;
if (!container.lensFlareSystems) {
return;
}
container.lensFlareSystems.forEach(function(o) {
_this.scene.addLensFlareSystem(o);
});
};
LensFlareSystemSceneComponent2.prototype.removeFromContainer = function(container) {
var _this = this;
if (!container.lensFlareSystems) {
return;
}
container.lensFlareSystems.forEach(function(o) {
_this.scene.removeLensFlareSystem(o);
});
};
LensFlareSystemSceneComponent2.prototype.serialize = function(serializationObject) {
serializationObject.lensFlareSystems = [];
var lensFlareSystems = this.scene.lensFlareSystems;
for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
var lensFlareSystem = lensFlareSystems_1[_i];
serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
}
};
LensFlareSystemSceneComponent2.prototype.dispose = function() {
var lensFlareSystems = this.scene.lensFlareSystems;
while (lensFlareSystems.length) {
lensFlareSystems[0].dispose();
}
};
LensFlareSystemSceneComponent2.prototype._draw = function(camera2) {
if (this.scene.lensFlaresEnabled) {
var lensFlareSystems = this.scene.lensFlareSystems;
BABYLON2.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
var lensFlareSystem = lensFlareSystems_2[_i];
if ((camera2.layerMask & lensFlareSystem.layerMask) !== 0) {
lensFlareSystem.render();
}
}
BABYLON2.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
}
};
return LensFlareSystemSceneComponent2;
}()
);
BABYLON2.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var LensFlareSystem = (
/** @class */
function() {
function LensFlareSystem2(name, emitter, scene) {
this.name = name;
this.lensFlares = new Array();
this.borderLimit = 300;
this.viewportBorder = 0;
this.layerMask = 268435455;
this._vertexBuffers = {};
this._isEnabled = true;
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
var component = this._scene._getComponent(BABYLON2.SceneComponentConstants.NAME_LENSFLARESYSTEM);
if (!component) {
component = new BABYLON2.LensFlareSystemSceneComponent(this._scene);
scene._addComponent(component);
}
this._emitter = emitter;
this.id = name;
scene.lensFlareSystems.push(this);
this.meshesSelectionPredicate = function(m) {
return scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && (m.layerMask & scene.activeCamera.layerMask) != 0;
};
var engine = scene.getEngine();
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = new BABYLON2.VertexBuffer(engine, vertices, BABYLON2.VertexBuffer.PositionKind, false, false, 2);
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = engine.createIndexBuffer(indices);
this._effect = engine.createEffect("lensFlare", [BABYLON2.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
}
Object.defineProperty(LensFlareSystem2.prototype, "isEnabled", {
/**
* Define if the lens flare system is enabled.
*/
get: function() {
return this._isEnabled;
},
set: function(value) {
this._isEnabled = value;
},
enumerable: true,
configurable: true
});
LensFlareSystem2.prototype.getScene = function() {
return this._scene;
};
LensFlareSystem2.prototype.getEmitter = function() {
return this._emitter;
};
LensFlareSystem2.prototype.setEmitter = function(newEmitter) {
this._emitter = newEmitter;
};
LensFlareSystem2.prototype.getEmitterPosition = function() {
return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
};
LensFlareSystem2.prototype.computeEffectivePosition = function(globalViewport) {
var position = this.getEmitterPosition();
position = BABYLON2.Vector3.Project(position, BABYLON2.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
this._positionX = position.x;
this._positionY = position.y;
position = BABYLON2.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
if (this.viewportBorder > 0) {
globalViewport.x -= this.viewportBorder;
globalViewport.y -= this.viewportBorder;
globalViewport.width += this.viewportBorder * 2;
globalViewport.height += this.viewportBorder * 2;
position.x += this.viewportBorder;
position.y += this.viewportBorder;
this._positionX += this.viewportBorder;
this._positionY += this.viewportBorder;
}
if (position.z > 0) {
if (this._positionX > globalViewport.x && this._positionX < globalViewport.x + globalViewport.width) {
if (this._positionY > globalViewport.y && this._positionY < globalViewport.y + globalViewport.height) {
return true;
}
}
return true;
}
return false;
};
LensFlareSystem2.prototype._isVisible = function() {
if (!this._isEnabled || !this._scene.activeCamera) {
return false;
}
var emitterPosition = this.getEmitterPosition();
var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
var distance = direction.length();
direction.normalize();
var ray = new BABYLON2.Ray(this._scene.activeCamera.globalPosition, direction);
var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
};
LensFlareSystem2.prototype.render = function() {
if (!this._effect.isReady() || !this._scene.activeCamera) {
return false;
}
var engine = this._scene.getEngine();
var viewport = this._scene.activeCamera.viewport;
var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
if (!this.computeEffectivePosition(globalViewport)) {
return false;
}
if (!this._isVisible()) {
return false;
}
var awayX;
var awayY;
if (this._positionX < this.borderLimit + globalViewport.x) {
awayX = this.borderLimit + globalViewport.x - this._positionX;
} else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
} else {
awayX = 0;
}
if (this._positionY < this.borderLimit + globalViewport.y) {
awayY = this.borderLimit + globalViewport.y - this._positionY;
} else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
} else {
awayY = 0;
}
var away = awayX > awayY ? awayX : awayY;
away -= this.viewportBorder;
if (away > this.borderLimit) {
away = this.borderLimit;
}
var intensity = 1 - BABYLON2.Scalar.Clamp(away / this.borderLimit, 0, 1);
if (intensity < 0) {
return false;
}
if (intensity > 1) {
intensity = 1;
}
if (this.viewportBorder > 0) {
globalViewport.x += this.viewportBorder;
globalViewport.y += this.viewportBorder;
globalViewport.width -= this.viewportBorder * 2;
globalViewport.height -= this.viewportBorder * 2;
this._positionX -= this.viewportBorder;
this._positionY -= this.viewportBorder;
}
var centerX = globalViewport.x + globalViewport.width / 2;
var centerY = globalViewport.y + globalViewport.height / 2;
var distX = centerX - this._positionX;
var distY = centerY - this._positionY;
engine.enableEffect(this._effect);
engine.setState(false);
engine.setDepthBuffer(false);
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
for (var index = 0; index < this.lensFlares.length; index++) {
var flare = this.lensFlares[index];
engine.setAlphaMode(flare.alphaMode);
var x = centerX - distX * flare.position;
var y = centerY - distY * flare.position;
var cw = flare.size;
var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1;
var cy = 1 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
var viewportMatrix = BABYLON2.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
this._effect.setMatrix("viewportMatrix", viewportMatrix);
this._effect.setTexture("textureSampler", flare.texture);
this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
}
engine.setDepthBuffer(true);
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
return true;
};
LensFlareSystem2.prototype.dispose = function() {
var vertexBuffer = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
while (this.lensFlares.length) {
this.lensFlares[0].dispose();
}
var index = this._scene.lensFlareSystems.indexOf(this);
this._scene.lensFlareSystems.splice(index, 1);
};
LensFlareSystem2.Parse = function(parsedLensFlareSystem, scene, rootUrl) {
var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
var lensFlareSystem = new LensFlareSystem2(name, emitter, scene);
lensFlareSystem.id = parsedLensFlareSystem.id || name;
lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
var parsedFlare = parsedLensFlareSystem.flares[index];
BABYLON2.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON2.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
}
return lensFlareSystem;
};
LensFlareSystem2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.id = this.id;
serializationObject.name = this.name;
serializationObject.emitterId = this.getEmitter().id;
serializationObject.borderLimit = this.borderLimit;
serializationObject.flares = [];
for (var index = 0; index < this.lensFlares.length; index++) {
var flare = this.lensFlares[index];
serializationObject.flares.push({
size: flare.size,
position: flare.position,
color: flare.color.asArray(),
textureName: BABYLON2.Tools.GetFilename(flare.texture ? flare.texture.name : "")
});
}
return serializationObject;
};
return LensFlareSystem2;
}()
);
BABYLON2.LensFlareSystem = LensFlareSystem;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PhysicsJoint = (
/** @class */
function() {
function PhysicsJoint2(type, jointData) {
this.type = type;
this.jointData = jointData;
jointData.nativeParams = jointData.nativeParams || {};
}
Object.defineProperty(PhysicsJoint2.prototype, "physicsJoint", {
/**
* Gets the physics joint
*/
get: function() {
return this._physicsJoint;
},
/**
* Sets the physics joint
*/
set: function(newJoint) {
if (this._physicsJoint) {
}
this._physicsJoint = newJoint;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PhysicsJoint2.prototype, "physicsPlugin", {
/**
* Sets the physics plugin
*/
set: function(physicsPlugin) {
this._physicsPlugin = physicsPlugin;
},
enumerable: true,
configurable: true
});
PhysicsJoint2.prototype.executeNativeFunction = function(func) {
func(this._physicsPlugin.world, this._physicsJoint);
};
PhysicsJoint2.DistanceJoint = 0;
PhysicsJoint2.HingeJoint = 1;
PhysicsJoint2.BallAndSocketJoint = 2;
PhysicsJoint2.WheelJoint = 3;
PhysicsJoint2.SliderJoint = 4;
PhysicsJoint2.PrismaticJoint = 5;
PhysicsJoint2.UniversalJoint = 6;
PhysicsJoint2.Hinge2Joint = PhysicsJoint2.WheelJoint;
PhysicsJoint2.PointToPointJoint = 8;
PhysicsJoint2.SpringJoint = 9;
PhysicsJoint2.LockJoint = 10;
return PhysicsJoint2;
}()
);
BABYLON2.PhysicsJoint = PhysicsJoint;
var DistanceJoint = (
/** @class */
function(_super) {
__extends(DistanceJoint2, _super);
function DistanceJoint2(jointData) {
return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
}
DistanceJoint2.prototype.updateDistance = function(maxDistance, minDistance) {
this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
};
return DistanceJoint2;
}(PhysicsJoint)
);
BABYLON2.DistanceJoint = DistanceJoint;
var MotorEnabledJoint = (
/** @class */
function(_super) {
__extends(MotorEnabledJoint2, _super);
function MotorEnabledJoint2(type, jointData) {
return _super.call(this, type, jointData) || this;
}
MotorEnabledJoint2.prototype.setMotor = function(force, maxForce) {
this._physicsPlugin.setMotor(this, force || 0, maxForce);
};
MotorEnabledJoint2.prototype.setLimit = function(upperLimit, lowerLimit) {
this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
};
return MotorEnabledJoint2;
}(PhysicsJoint)
);
BABYLON2.MotorEnabledJoint = MotorEnabledJoint;
var HingeJoint = (
/** @class */
function(_super) {
__extends(HingeJoint2, _super);
function HingeJoint2(jointData) {
return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
}
HingeJoint2.prototype.setMotor = function(force, maxForce) {
this._physicsPlugin.setMotor(this, force || 0, maxForce);
};
HingeJoint2.prototype.setLimit = function(upperLimit, lowerLimit) {
this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
};
return HingeJoint2;
}(MotorEnabledJoint)
);
BABYLON2.HingeJoint = HingeJoint;
var Hinge2Joint = (
/** @class */
function(_super) {
__extends(Hinge2Joint2, _super);
function Hinge2Joint2(jointData) {
return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
}
Hinge2Joint2.prototype.setMotor = function(force, maxForce, motorIndex) {
if (motorIndex === void 0) {
motorIndex = 0;
}
this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
};
Hinge2Joint2.prototype.setLimit = function(upperLimit, lowerLimit, motorIndex) {
if (motorIndex === void 0) {
motorIndex = 0;
}
this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
};
return Hinge2Joint2;
}(MotorEnabledJoint)
);
BABYLON2.Hinge2Joint = Hinge2Joint;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PhysicsImpostor = (
/** @class */
function() {
function PhysicsImpostor2(object, type, _options, _scene) {
if (_options === void 0) {
_options = { mass: 0 };
}
var _this = this;
this.object = object;
this.type = type;
this._options = _options;
this._scene = _scene;
this._bodyUpdateRequired = false;
this._onBeforePhysicsStepCallbacks = new Array();
this._onAfterPhysicsStepCallbacks = new Array();
this._onPhysicsCollideCallbacks = [];
this._deltaPosition = BABYLON2.Vector3.Zero();
this._isDisposed = false;
this._tmpQuat = new BABYLON2.Quaternion();
this._tmpQuat2 = new BABYLON2.Quaternion();
this.beforeStep = function() {
if (!_this._physicsEngine) {
return;
}
_this.object.translate(_this._deltaPosition, -1);
_this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
_this.object.computeWorldMatrix(false);
if (_this.object.parent && _this.object.rotationQuaternion) {
_this.getParentsRotation();
_this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
} else {
_this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON2.Quaternion());
}
if (!_this._options.disableBidirectionalTransformation) {
_this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(
_this,
/*bInfo.boundingBox.centerWorld*/
_this.object.getAbsolutePivotPoint(),
_this._tmpQuat
);
}
_this._onBeforePhysicsStepCallbacks.forEach(function(func) {
func(_this);
});
};
this.afterStep = function() {
if (!_this._physicsEngine) {
return;
}
_this._onAfterPhysicsStepCallbacks.forEach(function(func) {
func(_this);
});
_this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
if (_this.object.parent && _this.object.rotationQuaternion) {
_this.getParentsRotation();
_this._tmpQuat.conjugateInPlace();
_this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
}
_this.object.setAbsolutePosition(_this.object.position);
_this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
_this.object.translate(_this._deltaPosition, 1);
};
this.onCollideEvent = null;
this.onCollide = function(e2) {
if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
return;
}
if (!_this._physicsEngine) {
return;
}
var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e2.body);
if (otherImpostor) {
if (_this.onCollideEvent) {
_this.onCollideEvent(_this, otherImpostor);
}
_this._onPhysicsCollideCallbacks.filter(function(obj) {
return obj.otherImpostors.indexOf(otherImpostor) !== -1;
}).forEach(function(obj) {
obj.callback(_this, otherImpostor);
});
}
};
if (!this.object) {
BABYLON2.Tools.Error("No object was provided. A physics object is obligatory");
return;
}
if (!this._scene && object.getScene) {
this._scene = object.getScene();
}
if (!this._scene) {
return;
}
this._physicsEngine = this._scene.getPhysicsEngine();
if (!this._physicsEngine) {
BABYLON2.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
} else {
if (!this.object.rotationQuaternion) {
if (this.object.rotation) {
this.object.rotationQuaternion = BABYLON2.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
} else {
this.object.rotationQuaternion = new BABYLON2.Quaternion();
}
}
this._options.mass = _options.mass === void 0 ? 0 : _options.mass;
this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction;
this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution;
this._joints = [];
if (!this.object.parent || this._options.ignoreParent) {
this._init();
} else if (this.object.parent.physicsImpostor) {
BABYLON2.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
}
}
}
Object.defineProperty(PhysicsImpostor2.prototype, "isDisposed", {
/**
* Specifies if the physics imposter is disposed
*/
get: function() {
return this._isDisposed;
},
enumerable: true,
configurable: true
});
Object.defineProperty(PhysicsImpostor2.prototype, "mass", {
/**
* Gets the mass of the physics imposter
*/
get: function() {
return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
},
set: function(value) {
this.setMass(value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PhysicsImpostor2.prototype, "friction", {
/**
* Gets the coefficient of friction
*/
get: function() {
return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
},
/**
* Sets the coefficient of friction
*/
set: function(value) {
if (!this._physicsEngine) {
return;
}
this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(PhysicsImpostor2.prototype, "restitution", {
/**
* Gets the coefficient of restitution
*/
get: function() {
return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
},
/**
* Sets the coefficient of restitution
*/
set: function(value) {
if (!this._physicsEngine) {
return;
}
this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
},
enumerable: true,
configurable: true
});
PhysicsImpostor2.prototype._init = function() {
if (!this._physicsEngine) {
return;
}
this._physicsEngine.removeImpostor(this);
this.physicsBody = null;
this._parent = this._parent || this._getPhysicsParent();
if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
this._physicsEngine.addImpostor(this);
}
};
PhysicsImpostor2.prototype._getPhysicsParent = function() {
if (this.object.parent instanceof BABYLON2.AbstractMesh) {
var parentMesh = this.object.parent;
return parentMesh.physicsImpostor;
}
return null;
};
PhysicsImpostor2.prototype.isBodyInitRequired = function() {
return this._bodyUpdateRequired || !this._physicsBody && !this._parent;
};
PhysicsImpostor2.prototype.setScalingUpdated = function(updated) {
this.forceUpdate();
};
PhysicsImpostor2.prototype.forceUpdate = function() {
this._init();
if (this.parent && !this._options.ignoreParent) {
this.parent.forceUpdate();
}
};
Object.defineProperty(PhysicsImpostor2.prototype, "physicsBody", {
/*public get mesh(): AbstractMesh {
return this._mesh;
}*/
/**
* Gets the body that holds this impostor. Either its own, or its parent.
*/
get: function() {
return this._parent && !this._options.ignoreParent ? this._parent.physicsBody : this._physicsBody;
},
/**
* Set the physics body. Used mainly by the physics engine/plugin
*/
set: function(physicsBody) {
if (this._physicsBody && this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
}
this._physicsBody = physicsBody;
this.resetUpdateFlags();
},
enumerable: true,
configurable: true
});
Object.defineProperty(PhysicsImpostor2.prototype, "parent", {
/**
* Get the parent of the physics imposter
* @returns Physics imposter or null
*/
get: function() {
return !this._options.ignoreParent && this._parent ? this._parent : null;
},
/**
* Sets the parent of the physics imposter
*/
set: function(value) {
this._parent = value;
},
enumerable: true,
configurable: true
});
PhysicsImpostor2.prototype.resetUpdateFlags = function() {
this._bodyUpdateRequired = false;
};
PhysicsImpostor2.prototype.getObjectExtendSize = function() {
if (this.object.getBoundingInfo) {
var q = this.object.rotationQuaternion;
this.object.rotationQuaternion = PhysicsImpostor2.IDENTITY_QUATERNION;
this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
var boundingInfo = this.object.getBoundingInfo();
var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
this.object.rotationQuaternion = q;
this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
return size;
} else {
return PhysicsImpostor2.DEFAULT_OBJECT_SIZE;
}
};
PhysicsImpostor2.prototype.getObjectCenter = function() {
if (this.object.getBoundingInfo) {
var boundingInfo = this.object.getBoundingInfo();
return boundingInfo.boundingBox.centerWorld;
} else {
return this.object.position;
}
};
PhysicsImpostor2.prototype.getParam = function(paramName) {
return this._options[paramName];
};
PhysicsImpostor2.prototype.setParam = function(paramName, value) {
this._options[paramName] = value;
this._bodyUpdateRequired = true;
};
PhysicsImpostor2.prototype.setMass = function(mass) {
if (this.getParam("mass") !== mass) {
this.setParam("mass", mass);
}
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
}
};
PhysicsImpostor2.prototype.getLinearVelocity = function() {
return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON2.Vector3.Zero();
};
PhysicsImpostor2.prototype.setLinearVelocity = function(velocity) {
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
}
};
PhysicsImpostor2.prototype.getAngularVelocity = function() {
return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON2.Vector3.Zero();
};
PhysicsImpostor2.prototype.setAngularVelocity = function(velocity) {
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
}
};
PhysicsImpostor2.prototype.executeNativeFunction = function(func) {
if (this._physicsEngine) {
func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
}
};
PhysicsImpostor2.prototype.registerBeforePhysicsStep = function(func) {
this._onBeforePhysicsStepCallbacks.push(func);
};
PhysicsImpostor2.prototype.unregisterBeforePhysicsStep = function(func) {
var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
if (index > -1) {
this._onBeforePhysicsStepCallbacks.splice(index, 1);
} else {
BABYLON2.Tools.Warn("Function to remove was not found");
}
};
PhysicsImpostor2.prototype.registerAfterPhysicsStep = function(func) {
this._onAfterPhysicsStepCallbacks.push(func);
};
PhysicsImpostor2.prototype.unregisterAfterPhysicsStep = function(func) {
var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
if (index > -1) {
this._onAfterPhysicsStepCallbacks.splice(index, 1);
} else {
BABYLON2.Tools.Warn("Function to remove was not found");
}
};
PhysicsImpostor2.prototype.registerOnPhysicsCollide = function(collideAgainst, func) {
var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
};
PhysicsImpostor2.prototype.unregisterOnPhysicsCollide = function(collideAgainst, func) {
var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
var index = -1;
var found = this._onPhysicsCollideCallbacks.some(function(cbDef, idx) {
if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
var sameList = cbDef.otherImpostors.every(function(impostor) {
return collidedAgainstList.indexOf(impostor) > -1;
});
if (sameList) {
index = idx;
}
return sameList;
}
return false;
});
if (found) {
this._onPhysicsCollideCallbacks.splice(index, 1);
} else {
BABYLON2.Tools.Warn("Function to remove was not found");
}
};
PhysicsImpostor2.prototype.getParentsRotation = function() {
var parent = this.object.parent;
this._tmpQuat.copyFromFloats(0, 0, 0, 1);
while (parent) {
if (parent.rotationQuaternion) {
this._tmpQuat2.copyFrom(parent.rotationQuaternion);
} else {
BABYLON2.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
}
this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
parent = parent.parent;
}
return this._tmpQuat;
};
PhysicsImpostor2.prototype.applyForce = function(force, contactPoint) {
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
}
return this;
};
PhysicsImpostor2.prototype.applyImpulse = function(force, contactPoint) {
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
}
return this;
};
PhysicsImpostor2.prototype.createJoint = function(otherImpostor, jointType, jointData) {
var joint = new BABYLON2.PhysicsJoint(jointType, jointData);
this.addJoint(otherImpostor, joint);
return this;
};
PhysicsImpostor2.prototype.addJoint = function(otherImpostor, joint) {
this._joints.push({
otherImpostor,
joint
});
if (this._physicsEngine) {
this._physicsEngine.addJoint(this, otherImpostor, joint);
}
return this;
};
PhysicsImpostor2.prototype.sleep = function() {
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().sleepBody(this);
}
return this;
};
PhysicsImpostor2.prototype.wakeUp = function() {
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
}
return this;
};
PhysicsImpostor2.prototype.clone = function(newObject) {
if (!newObject) {
return null;
}
return new PhysicsImpostor2(newObject, this.type, this._options, this._scene);
};
PhysicsImpostor2.prototype.dispose = function() {
var _this = this;
if (!this._physicsEngine) {
return;
}
this._joints.forEach(function(j) {
if (_this._physicsEngine) {
_this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
}
});
this._physicsEngine.removeImpostor(this);
if (this.parent) {
this.parent.forceUpdate();
} else {
}
this._isDisposed = true;
};
PhysicsImpostor2.prototype.setDeltaPosition = function(position) {
this._deltaPosition.copyFrom(position);
};
PhysicsImpostor2.prototype.setDeltaRotation = function(rotation) {
if (!this._deltaRotation) {
this._deltaRotation = new BABYLON2.Quaternion();
}
this._deltaRotation.copyFrom(rotation);
this._deltaRotationConjugated = this._deltaRotation.conjugate();
};
PhysicsImpostor2.prototype.getBoxSizeToRef = function(result) {
if (this._physicsEngine) {
this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
}
return this;
};
PhysicsImpostor2.prototype.getRadius = function() {
return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
};
PhysicsImpostor2.prototype.syncBoneWithImpostor = function(bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
var tempVec = PhysicsImpostor2._tmpVecs[0];
var mesh2 = this.object;
if (mesh2.rotationQuaternion) {
if (adjustRotation) {
var tempQuat = PhysicsImpostor2._tmpQuat;
mesh2.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
bone.setRotationQuaternion(tempQuat, BABYLON2.Space.WORLD, boneMesh);
} else {
bone.setRotationQuaternion(mesh2.rotationQuaternion, BABYLON2.Space.WORLD, boneMesh);
}
}
tempVec.x = 0;
tempVec.y = 0;
tempVec.z = 0;
if (jointPivot) {
tempVec.x = jointPivot.x;
tempVec.y = jointPivot.y;
tempVec.z = jointPivot.z;
bone.getDirectionToRef(tempVec, boneMesh, tempVec);
if (distToJoint === void 0 || distToJoint === null) {
distToJoint = jointPivot.length();
}
tempVec.x *= distToJoint;
tempVec.y *= distToJoint;
tempVec.z *= distToJoint;
}
if (bone.getParent()) {
tempVec.addInPlace(mesh2.getAbsolutePosition());
bone.setAbsolutePosition(tempVec, boneMesh);
} else {
boneMesh.setAbsolutePosition(mesh2.getAbsolutePosition());
boneMesh.position.x -= tempVec.x;
boneMesh.position.y -= tempVec.y;
boneMesh.position.z -= tempVec.z;
}
};
PhysicsImpostor2.prototype.syncImpostorWithBone = function(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
var mesh2 = this.object;
if (mesh2.rotationQuaternion) {
if (adjustRotation) {
var tempQuat = PhysicsImpostor2._tmpQuat;
bone.getRotationQuaternionToRef(BABYLON2.Space.WORLD, boneMesh, tempQuat);
tempQuat.multiplyToRef(adjustRotation, mesh2.rotationQuaternion);
} else {
bone.getRotationQuaternionToRef(BABYLON2.Space.WORLD, boneMesh, mesh2.rotationQuaternion);
}
}
var pos = PhysicsImpostor2._tmpVecs[0];
var boneDir = PhysicsImpostor2._tmpVecs[1];
if (!boneAxis) {
boneAxis = PhysicsImpostor2._tmpVecs[2];
boneAxis.x = 0;
boneAxis.y = 1;
boneAxis.z = 0;
}
bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
bone.getAbsolutePositionToRef(boneMesh, pos);
if ((distToJoint === void 0 || distToJoint === null) && jointPivot) {
distToJoint = jointPivot.length();
}
if (distToJoint !== void 0 && distToJoint !== null) {
pos.x += boneDir.x * distToJoint;
pos.y += boneDir.y * distToJoint;
pos.z += boneDir.z * distToJoint;
}
mesh2.setAbsolutePosition(pos);
};
PhysicsImpostor2.DEFAULT_OBJECT_SIZE = new BABYLON2.Vector3(1, 1, 1);
PhysicsImpostor2.IDENTITY_QUATERNION = BABYLON2.Quaternion.Identity();
PhysicsImpostor2._tmpVecs = [BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero(), BABYLON2.Vector3.Zero()];
PhysicsImpostor2._tmpQuat = BABYLON2.Quaternion.Identity();
PhysicsImpostor2.NoImpostor = 0;
PhysicsImpostor2.SphereImpostor = 1;
PhysicsImpostor2.BoxImpostor = 2;
PhysicsImpostor2.PlaneImpostor = 3;
PhysicsImpostor2.MeshImpostor = 4;
PhysicsImpostor2.CylinderImpostor = 7;
PhysicsImpostor2.ParticleImpostor = 8;
PhysicsImpostor2.HeightmapImpostor = 9;
return PhysicsImpostor2;
}()
);
BABYLON2.PhysicsImpostor = PhysicsImpostor;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PhysicsEngine = (
/** @class */
function() {
function PhysicsEngine2(gravity, _physicsPlugin) {
if (_physicsPlugin === void 0) {
_physicsPlugin = new BABYLON2.CannonJSPlugin();
}
this._physicsPlugin = _physicsPlugin;
this._impostors = [];
this._joints = [];
if (!this._physicsPlugin.isSupported()) {
throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. Please make sure it is included.");
}
gravity = gravity || new BABYLON2.Vector3(0, -9.807, 0);
this.setGravity(gravity);
this.setTimeStep();
}
PhysicsEngine2.prototype.setGravity = function(gravity) {
this.gravity = gravity;
this._physicsPlugin.setGravity(this.gravity);
};
PhysicsEngine2.prototype.setTimeStep = function(newTimeStep) {
if (newTimeStep === void 0) {
newTimeStep = 1 / 60;
}
this._physicsPlugin.setTimeStep(newTimeStep);
};
PhysicsEngine2.prototype.getTimeStep = function() {
return this._physicsPlugin.getTimeStep();
};
PhysicsEngine2.prototype.dispose = function() {
this._impostors.forEach(function(impostor) {
impostor.dispose();
});
this._physicsPlugin.dispose();
};
PhysicsEngine2.prototype.getPhysicsPluginName = function() {
return this._physicsPlugin.name;
};
PhysicsEngine2.prototype.addImpostor = function(impostor) {
impostor.uniqueId = this._impostors.push(impostor);
if (!impostor.parent) {
this._physicsPlugin.generatePhysicsBody(impostor);
}
};
PhysicsEngine2.prototype.removeImpostor = function(impostor) {
var index = this._impostors.indexOf(impostor);
if (index > -1) {
var removed = this._impostors.splice(index, 1);
if (removed.length) {
removed[0].physicsBody = null;
}
}
};
PhysicsEngine2.prototype.addJoint = function(mainImpostor, connectedImpostor, joint) {
var impostorJoint = {
mainImpostor,
connectedImpostor,
joint
};
joint.physicsPlugin = this._physicsPlugin;
this._joints.push(impostorJoint);
this._physicsPlugin.generateJoint(impostorJoint);
};
PhysicsEngine2.prototype.removeJoint = function(mainImpostor, connectedImpostor, joint) {
var matchingJoints = this._joints.filter(function(impostorJoint) {
return impostorJoint.connectedImpostor === connectedImpostor && impostorJoint.joint === joint && impostorJoint.mainImpostor === mainImpostor;
});
if (matchingJoints.length) {
this._physicsPlugin.removeJoint(matchingJoints[0]);
}
};
PhysicsEngine2.prototype._step = function(delta) {
var _this = this;
this._impostors.forEach(function(impostor) {
if (impostor.isBodyInitRequired()) {
_this._physicsPlugin.generatePhysicsBody(impostor);
}
});
if (delta > 0.1) {
delta = 0.1;
} else if (delta <= 0) {
delta = 1 / 60;
}
this._physicsPlugin.executeStep(delta, this._impostors);
};
PhysicsEngine2.prototype.getPhysicsPlugin = function() {
return this._physicsPlugin;
};
PhysicsEngine2.prototype.getImpostors = function() {
return this._impostors;
};
PhysicsEngine2.prototype.getImpostorForPhysicsObject = function(object) {
for (var i2 = 0; i2 < this._impostors.length; ++i2) {
if (this._impostors[i2].object === object) {
return this._impostors[i2];
}
}
return null;
};
PhysicsEngine2.prototype.getImpostorWithPhysicsBody = function(body) {
for (var i2 = 0; i2 < this._impostors.length; ++i2) {
if (this._impostors[i2].physicsBody === body) {
return this._impostors[i2];
}
}
return null;
};
PhysicsEngine2.Epsilon = 1e-3;
return PhysicsEngine2;
}()
);
BABYLON2.PhysicsEngine = PhysicsEngine;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var CannonJSPlugin = (
/** @class */
function() {
function CannonJSPlugin2(_useDeltaForWorldStep, iterations) {
if (_useDeltaForWorldStep === void 0) {
_useDeltaForWorldStep = true;
}
if (iterations === void 0) {
iterations = 10;
}
this._useDeltaForWorldStep = _useDeltaForWorldStep;
this.name = "CannonJSPlugin";
this._physicsMaterials = new Array();
this._fixedTimeStep = 1 / 60;
this.BJSCANNON = CANNON;
this._minus90X = new BABYLON2.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
this._plus90X = new BABYLON2.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
this._tmpPosition = BABYLON2.Vector3.Zero();
this._tmpDeltaPosition = BABYLON2.Vector3.Zero();
this._tmpUnityRotation = new BABYLON2.Quaternion();
if (!this.isSupported()) {
BABYLON2.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
return;
}
this._extendNamespace();
this.world = new this.BJSCANNON.World();
this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
this.world.solver.iterations = iterations;
}
CannonJSPlugin2.prototype.setGravity = function(gravity) {
this.world.gravity.copy(gravity);
};
CannonJSPlugin2.prototype.setTimeStep = function(timeStep) {
this._fixedTimeStep = timeStep;
};
CannonJSPlugin2.prototype.getTimeStep = function() {
return this._fixedTimeStep;
};
CannonJSPlugin2.prototype.executeStep = function(delta, impostors) {
this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
};
CannonJSPlugin2.prototype.applyImpulse = function(impostor, force, contactPoint) {
var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
impostor.physicsBody.applyImpulse(impulse, worldPoint);
};
CannonJSPlugin2.prototype.applyForce = function(impostor, force, contactPoint) {
var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
impostor.physicsBody.applyForce(impulse, worldPoint);
};
CannonJSPlugin2.prototype.generatePhysicsBody = function(impostor) {
if (impostor.parent) {
if (impostor.physicsBody) {
this.removePhysicsBody(impostor);
impostor.forceUpdate();
}
return;
}
if (impostor.isBodyInitRequired()) {
var shape = this._createShape(impostor);
var oldBody = impostor.physicsBody;
if (oldBody) {
this.removePhysicsBody(impostor);
}
var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
var bodyCreationObject = {
mass: impostor.getParam("mass"),
material
};
var nativeOptions = impostor.getParam("nativeOptions");
for (var key in nativeOptions) {
if (nativeOptions.hasOwnProperty(key)) {
bodyCreationObject[key] = nativeOptions[key];
}
}
impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
impostor.physicsBody.addEventListener("collide", impostor.onCollide);
this.world.addEventListener("preStep", impostor.beforeStep);
this.world.addEventListener("postStep", impostor.afterStep);
impostor.physicsBody.addShape(shape);
this.world.add(impostor.physicsBody);
if (oldBody) {
["force", "torque", "velocity", "angularVelocity"].forEach(function(param) {
impostor.physicsBody[param].copy(oldBody[param]);
});
}
this._processChildMeshes(impostor);
}
this._updatePhysicsBodyTransformation(impostor);
};
CannonJSPlugin2.prototype._processChildMeshes = function(mainImpostor) {
var _this = this;
var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
var currentRotation = mainImpostor.object.rotationQuaternion;
if (meshChildren.length) {
var processMesh = function(localPosition, mesh2) {
if (!currentRotation || !mesh2.rotationQuaternion) {
return;
}
var childImpostor = mesh2.getPhysicsImpostor();
if (childImpostor) {
var parent = childImpostor.parent;
if (parent !== mainImpostor) {
var pPosition = mesh2.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
var localRotation = mesh2.rotationQuaternion.multiply(BABYLON2.Quaternion.Inverse(currentRotation));
if (childImpostor.physicsBody) {
_this.removePhysicsBody(childImpostor);
childImpostor.physicsBody = null;
}
childImpostor.parent = mainImpostor;
childImpostor.resetUpdateFlags();
mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
}
}
currentRotation.multiplyInPlace(mesh2.rotationQuaternion);
mesh2.getChildMeshes(true).filter(function(m) {
return !!m.physicsImpostor;
}).forEach(processMesh.bind(_this, mesh2.getAbsolutePosition()));
};
meshChildren.filter(function(m) {
return !!m.physicsImpostor;
}).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
}
};
CannonJSPlugin2.prototype.removePhysicsBody = function(impostor) {
impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
this.world.removeEventListener("preStep", impostor.beforeStep);
this.world.removeEventListener("postStep", impostor.afterStep);
this.world.remove(impostor.physicsBody);
};
CannonJSPlugin2.prototype.generateJoint = function(impostorJoint) {
var mainBody = impostorJoint.mainImpostor.physicsBody;
var connectedBody = impostorJoint.connectedImpostor.physicsBody;
if (!mainBody || !connectedBody) {
return;
}
var constraint;
var jointData = impostorJoint.joint.jointData;
var constraintData = {
pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
maxForce: jointData.nativeParams.maxForce,
collideConnected: !!jointData.collision
};
switch (impostorJoint.joint.type) {
case BABYLON2.PhysicsJoint.HingeJoint:
case BABYLON2.PhysicsJoint.Hinge2Joint:
constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
break;
case BABYLON2.PhysicsJoint.DistanceJoint:
constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
break;
case BABYLON2.PhysicsJoint.SpringJoint:
var springData = jointData;
constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
restLength: springData.length,
stiffness: springData.stiffness,
damping: springData.damping,
localAnchorA: constraintData.pivotA,
localAnchorB: constraintData.pivotB
});
break;
case BABYLON2.PhysicsJoint.LockJoint:
constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
break;
case BABYLON2.PhysicsJoint.PointToPointJoint:
case BABYLON2.PhysicsJoint.BallAndSocketJoint:
default:
constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
break;
}
constraint.collideConnected = !!jointData.collision;
impostorJoint.joint.physicsJoint = constraint;
if (impostorJoint.joint.type !== BABYLON2.PhysicsJoint.SpringJoint) {
this.world.addConstraint(constraint);
} else {
impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function() {
constraint.applyForce();
};
impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
}
};
CannonJSPlugin2.prototype.removeJoint = function(impostorJoint) {
if (impostorJoint.joint.type !== BABYLON2.PhysicsJoint.SpringJoint) {
this.world.removeConstraint(impostorJoint.joint.physicsJoint);
} else {
impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
}
};
CannonJSPlugin2.prototype._addMaterial = function(name, friction, restitution) {
var index;
var mat;
for (index = 0; index < this._physicsMaterials.length; index++) {
mat = this._physicsMaterials[index];
if (mat.friction === friction && mat.restitution === restitution) {
return mat;
}
}
var currentMat = new this.BJSCANNON.Material(name);
currentMat.friction = friction;
currentMat.restitution = restitution;
this._physicsMaterials.push(currentMat);
return currentMat;
};
CannonJSPlugin2.prototype._checkWithEpsilon = function(value) {
return value < BABYLON2.PhysicsEngine.Epsilon ? BABYLON2.PhysicsEngine.Epsilon : value;
};
CannonJSPlugin2.prototype._createShape = function(impostor) {
var object = impostor.object;
var returnValue;
var extendSize = impostor.getObjectExtendSize();
switch (impostor.type) {
case BABYLON2.PhysicsImpostor.SphereImpostor:
var radiusX = extendSize.x;
var radiusY = extendSize.y;
var radiusZ = extendSize.z;
returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
break;
case BABYLON2.PhysicsImpostor.CylinderImpostor:
returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
break;
case BABYLON2.PhysicsImpostor.BoxImpostor:
var box = extendSize.scale(0.5);
returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
break;
case BABYLON2.PhysicsImpostor.PlaneImpostor:
BABYLON2.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
returnValue = new this.BJSCANNON.Plane();
break;
case BABYLON2.PhysicsImpostor.MeshImpostor:
var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON2.VertexBuffer.PositionKind) : [];
var rawFaces = object.getIndices ? object.getIndices() : [];
if (!rawVerts) {
return;
}
var oldPosition = object.position.clone();
var oldRotation = object.rotation && object.rotation.clone();
var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
object.position.copyFromFloats(0, 0, 0);
object.rotation && object.rotation.copyFromFloats(0, 0, 0);
object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
var transform = object.computeWorldMatrix(true);
var temp = new Array();
var index;
for (index = 0; index < rawVerts.length; index += 3) {
BABYLON2.Vector3.TransformCoordinates(BABYLON2.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
}
BABYLON2.Tools.Warn("MeshImpostor only collides against spheres.");
returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
object.position.copyFrom(oldPosition);
oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
break;
case BABYLON2.PhysicsImpostor.HeightmapImpostor:
var oldPosition2 = object.position.clone();
var oldRotation2 = object.rotation && object.rotation.clone();
var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
object.position.copyFromFloats(0, 0, 0);
object.rotation && object.rotation.copyFromFloats(0, 0, 0);
object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
returnValue = this._createHeightmap(object);
object.position.copyFrom(oldPosition2);
oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
object.computeWorldMatrix(true);
break;
case BABYLON2.PhysicsImpostor.ParticleImpostor:
returnValue = new this.BJSCANNON.Particle();
break;
}
return returnValue;
};
CannonJSPlugin2.prototype._createHeightmap = function(object, pointDepth) {
var pos = object.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var transform = object.computeWorldMatrix(true);
var temp = new Array();
var index;
for (index = 0; index < pos.length; index += 3) {
BABYLON2.Vector3.TransformCoordinates(BABYLON2.Vector3.FromArray(pos, index), transform).toArray(temp, index);
}
pos = temp;
var matrix = new Array();
var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
var boundingInfo = object.getBoundingInfo();
var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
var minY = boundingInfo.boundingBox.extendSizeWorld.z;
var elementSize = dim * 2 / arraySize;
for (var i2 = 0; i2 < pos.length; i2 = i2 + 3) {
var x = Math.round(pos[i2 + 0] / elementSize + arraySize / 2);
var z = Math.round((pos[i2 + 1] / elementSize - arraySize / 2) * -1);
var y = -pos[i2 + 2] + minY;
if (!matrix[x]) {
matrix[x] = [];
}
if (!matrix[x][z]) {
matrix[x][z] = y;
}
matrix[x][z] = Math.max(y, matrix[x][z]);
}
for (var x = 0; x <= arraySize; ++x) {
if (!matrix[x]) {
var loc = 1;
while (!matrix[(x + loc) % arraySize]) {
loc++;
}
matrix[x] = matrix[(x + loc) % arraySize].slice();
}
for (var z = 0; z <= arraySize; ++z) {
if (!matrix[x][z]) {
var loc = 1;
var newValue;
while (newValue === void 0) {
newValue = matrix[x][(z + loc++) % arraySize];
}
matrix[x][z] = newValue;
}
}
}
var shape = new this.BJSCANNON.Heightfield(matrix, {
elementSize
});
shape.minY = minY;
return shape;
};
CannonJSPlugin2.prototype._updatePhysicsBodyTransformation = function(impostor) {
var object = impostor.object;
object.computeWorldMatrix && object.computeWorldMatrix(true);
var bInfo = object.getBoundingInfo();
if (!bInfo) {
return;
}
var center = impostor.getObjectCenter();
this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
this._tmpPosition.copyFrom(center);
var quaternion = object.rotationQuaternion;
if (!quaternion) {
return;
}
if (impostor.type === BABYLON2.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON2.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON2.PhysicsImpostor.CylinderImpostor) {
quaternion = quaternion.multiply(this._minus90X);
impostor.setDeltaRotation(this._plus90X);
}
if (impostor.type === BABYLON2.PhysicsImpostor.HeightmapImpostor) {
var mesh2 = object;
var boundingInfo = mesh2.getBoundingInfo();
var rotationQuaternion = mesh2.rotationQuaternion;
mesh2.rotationQuaternion = this._tmpUnityRotation;
mesh2.computeWorldMatrix(true);
var c = center.clone();
var oldPivot = mesh2.getPivotMatrix() || BABYLON2.Matrix.Translation(0, 0, 0);
var p = BABYLON2.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
mesh2.setPreTransformMatrix(p);
mesh2.computeWorldMatrix(true);
var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh2.position).negate();
this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
mesh2.rotationQuaternion = rotationQuaternion;
mesh2.setPreTransformMatrix(oldPivot);
mesh2.computeWorldMatrix(true);
} else if (impostor.type === BABYLON2.PhysicsImpostor.MeshImpostor) {
this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
}
impostor.setDeltaPosition(this._tmpDeltaPosition);
impostor.physicsBody.position.copy(this._tmpPosition);
impostor.physicsBody.quaternion.copy(quaternion);
};
CannonJSPlugin2.prototype.setTransformationFromPhysicsBody = function(impostor) {
impostor.object.position.copyFrom(impostor.physicsBody.position);
if (impostor.object.rotationQuaternion) {
impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
}
};
CannonJSPlugin2.prototype.setPhysicsBodyTransformation = function(impostor, newPosition, newRotation) {
impostor.physicsBody.position.copy(newPosition);
impostor.physicsBody.quaternion.copy(newRotation);
};
CannonJSPlugin2.prototype.isSupported = function() {
return this.BJSCANNON !== void 0;
};
CannonJSPlugin2.prototype.setLinearVelocity = function(impostor, velocity) {
impostor.physicsBody.velocity.copy(velocity);
};
CannonJSPlugin2.prototype.setAngularVelocity = function(impostor, velocity) {
impostor.physicsBody.angularVelocity.copy(velocity);
};
CannonJSPlugin2.prototype.getLinearVelocity = function(impostor) {
var v = impostor.physicsBody.velocity;
if (!v) {
return null;
}
return new BABYLON2.Vector3(v.x, v.y, v.z);
};
CannonJSPlugin2.prototype.getAngularVelocity = function(impostor) {
var v = impostor.physicsBody.angularVelocity;
if (!v) {
return null;
}
return new BABYLON2.Vector3(v.x, v.y, v.z);
};
CannonJSPlugin2.prototype.setBodyMass = function(impostor, mass) {
impostor.physicsBody.mass = mass;
impostor.physicsBody.updateMassProperties();
};
CannonJSPlugin2.prototype.getBodyMass = function(impostor) {
return impostor.physicsBody.mass;
};
CannonJSPlugin2.prototype.getBodyFriction = function(impostor) {
return impostor.physicsBody.material.friction;
};
CannonJSPlugin2.prototype.setBodyFriction = function(impostor, friction) {
impostor.physicsBody.material.friction = friction;
};
CannonJSPlugin2.prototype.getBodyRestitution = function(impostor) {
return impostor.physicsBody.material.restitution;
};
CannonJSPlugin2.prototype.setBodyRestitution = function(impostor, restitution) {
impostor.physicsBody.material.restitution = restitution;
};
CannonJSPlugin2.prototype.sleepBody = function(impostor) {
impostor.physicsBody.sleep();
};
CannonJSPlugin2.prototype.wakeUpBody = function(impostor) {
impostor.physicsBody.wakeUp();
};
CannonJSPlugin2.prototype.updateDistanceJoint = function(joint, maxDistance, minDistance) {
joint.physicsJoint.distance = maxDistance;
};
CannonJSPlugin2.prototype.setMotor = function(joint, speed, maxForce, motorIndex) {
if (!motorIndex) {
joint.physicsJoint.enableMotor();
joint.physicsJoint.setMotorSpeed(speed);
if (maxForce) {
this.setLimit(joint, maxForce);
}
}
};
CannonJSPlugin2.prototype.setLimit = function(joint, upperLimit, lowerLimit) {
joint.physicsJoint.motorEquation.maxForce = upperLimit;
joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
};
CannonJSPlugin2.prototype.syncMeshWithImpostor = function(mesh2, impostor) {
var body = impostor.physicsBody;
mesh2.position.x = body.position.x;
mesh2.position.y = body.position.y;
mesh2.position.z = body.position.z;
if (mesh2.rotationQuaternion) {
mesh2.rotationQuaternion.x = body.quaternion.x;
mesh2.rotationQuaternion.y = body.quaternion.y;
mesh2.rotationQuaternion.z = body.quaternion.z;
mesh2.rotationQuaternion.w = body.quaternion.w;
}
};
CannonJSPlugin2.prototype.getRadius = function(impostor) {
var shape = impostor.physicsBody.shapes[0];
return shape.boundingSphereRadius;
};
CannonJSPlugin2.prototype.getBoxSizeToRef = function(impostor, result) {
var shape = impostor.physicsBody.shapes[0];
result.x = shape.halfExtents.x * 2;
result.y = shape.halfExtents.y * 2;
result.z = shape.halfExtents.z * 2;
};
CannonJSPlugin2.prototype.dispose = function() {
};
CannonJSPlugin2.prototype._extendNamespace = function() {
var step_tmp1 = new this.BJSCANNON.Vec3();
var Engine = this.BJSCANNON;
this.BJSCANNON.World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps) {
maxSubSteps = maxSubSteps || 10;
timeSinceLastCalled = timeSinceLastCalled || 0;
if (timeSinceLastCalled === 0) {
this.internalStep(dt);
this.time += dt;
} else {
var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
var t0 = performance.now();
for (var i2 = 0; i2 !== internalSteps; i2++) {
this.internalStep(dt);
if (performance.now() - t0 > dt * 1e3) {
break;
}
}
this.time += timeSinceLastCalled;
var h = this.time % dt;
var h_div_dt = h / dt;
var interpvelo = step_tmp1;
var bodies = this.bodies;
for (var j = 0; j !== bodies.length; j++) {
var b2 = bodies[j];
if (b2.type !== Engine.Body.STATIC && b2.sleepState !== Engine.Body.SLEEPING) {
b2.position.vsub(b2.previousPosition, interpvelo);
interpvelo.scale(h_div_dt, interpvelo);
b2.position.vadd(interpvelo, b2.interpolatedPosition);
} else {
b2.interpolatedPosition.copy(b2.position);
b2.interpolatedQuaternion.copy(b2.quaternion);
}
}
}
};
};
return CannonJSPlugin2;
}()
);
BABYLON2.CannonJSPlugin = CannonJSPlugin;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var OimoJSPlugin = (
/** @class */
function() {
function OimoJSPlugin2(iterations) {
this.name = "OimoJSPlugin";
this._tmpImpostorsArray = [];
this._tmpPositionVector = BABYLON2.Vector3.Zero();
this.BJSOIMO = OIMO;
this.world = new this.BJSOIMO.World({
iterations
});
this.world.clear();
}
OimoJSPlugin2.prototype.setGravity = function(gravity) {
this.world.gravity.copy(gravity);
};
OimoJSPlugin2.prototype.setTimeStep = function(timeStep) {
this.world.timeStep = timeStep;
};
OimoJSPlugin2.prototype.getTimeStep = function() {
return this.world.timeStep;
};
OimoJSPlugin2.prototype.executeStep = function(delta, impostors) {
var _this = this;
impostors.forEach(function(impostor) {
impostor.beforeStep();
});
this.world.step();
impostors.forEach(function(impostor) {
impostor.afterStep();
_this._tmpImpostorsArray[impostor.uniqueId] = impostor;
});
var contact = this.world.contacts;
while (contact !== null) {
if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
contact = contact.next;
continue;
}
var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
if (!mainImpostor || !collidingImpostor) {
contact = contact.next;
continue;
}
mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
contact = contact.next;
}
};
OimoJSPlugin2.prototype.applyImpulse = function(impostor, force, contactPoint) {
var mass = impostor.physicsBody.mass;
impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
};
OimoJSPlugin2.prototype.applyForce = function(impostor, force, contactPoint) {
BABYLON2.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
this.applyImpulse(impostor, force, contactPoint);
};
OimoJSPlugin2.prototype.generatePhysicsBody = function(impostor) {
var _this = this;
if (impostor.parent) {
if (impostor.physicsBody) {
this.removePhysicsBody(impostor);
impostor.forceUpdate();
}
return;
}
if (impostor.isBodyInitRequired()) {
var bodyConfig = {
name: impostor.uniqueId,
//Oimo must have mass, also for static objects.
config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
size: [],
type: [],
pos: [],
posShape: [],
rot: [],
rotShape: [],
move: impostor.getParam("mass") !== 0,
density: impostor.getParam("mass"),
friction: impostor.getParam("friction"),
restitution: impostor.getParam("restitution"),
//Supporting older versions of Oimo
world: this.world
};
var impostors = [impostor];
var addToArray = function(parent) {
if (!parent.getChildMeshes) {
return;
}
parent.getChildMeshes().forEach(function(m) {
if (m.physicsImpostor) {
impostors.push(m.physicsImpostor);
}
});
};
addToArray(impostor.object);
var checkWithEpsilon_1 = function(value) {
return Math.max(value, BABYLON2.PhysicsEngine.Epsilon);
};
var globalQuaternion_1 = new BABYLON2.Quaternion();
impostors.forEach(function(i2) {
if (!i2.object.rotationQuaternion) {
return;
}
var oldQuaternion = i2.object.rotationQuaternion;
globalQuaternion_1 = oldQuaternion.clone();
var rot = oldQuaternion.toEulerAngles();
var extendSize = i2.getObjectExtendSize();
var radToDeg = 57.29577951308232;
if (i2 === impostor) {
var center = impostor.getObjectCenter();
impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
_this._tmpPositionVector.divideInPlace(impostor.object.scaling);
bodyConfig.pos.push(center.x);
bodyConfig.pos.push(center.y);
bodyConfig.pos.push(center.z);
bodyConfig.posShape.push(0, 0, 0);
bodyConfig.rot.push(0);
bodyConfig.rot.push(0);
bodyConfig.rot.push(0);
bodyConfig.rotShape.push(0, 0, 0);
} else {
var localPosition = i2.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
bodyConfig.posShape.push(localPosition.x);
bodyConfig.posShape.push(localPosition.y);
bodyConfig.posShape.push(localPosition.z);
bodyConfig.pos.push(0, 0, 0);
bodyConfig.rot.push(0);
bodyConfig.rot.push(0);
bodyConfig.rot.push(0);
bodyConfig.rotShape.push(rot.x * radToDeg);
bodyConfig.rotShape.push(rot.y * radToDeg);
bodyConfig.rotShape.push(rot.z * radToDeg);
}
switch (i2.type) {
case BABYLON2.PhysicsImpostor.ParticleImpostor:
BABYLON2.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
case BABYLON2.PhysicsImpostor.SphereImpostor:
var radiusX = extendSize.x;
var radiusY = extendSize.y;
var radiusZ = extendSize.z;
var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
bodyConfig.type.push("sphere");
bodyConfig.size.push(size);
bodyConfig.size.push(size);
bodyConfig.size.push(size);
break;
case BABYLON2.PhysicsImpostor.CylinderImpostor:
var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
var sizeY = checkWithEpsilon_1(extendSize.y);
bodyConfig.type.push("cylinder");
bodyConfig.size.push(sizeX);
bodyConfig.size.push(sizeY);
bodyConfig.size.push(sizeY);
break;
case BABYLON2.PhysicsImpostor.PlaneImpostor:
case BABYLON2.PhysicsImpostor.BoxImpostor:
default:
var sizeX = checkWithEpsilon_1(extendSize.x);
var sizeY = checkWithEpsilon_1(extendSize.y);
var sizeZ = checkWithEpsilon_1(extendSize.z);
bodyConfig.type.push("box");
bodyConfig.size.push(sizeX);
bodyConfig.size.push(sizeY);
bodyConfig.size.push(sizeZ);
break;
}
i2.object.rotationQuaternion = oldQuaternion;
});
impostor.physicsBody = this.world.add(bodyConfig);
impostor.physicsBody.resetQuaternion(globalQuaternion_1);
impostor.physicsBody.updatePosition(0);
} else {
this._tmpPositionVector.copyFromFloats(0, 0, 0);
}
impostor.setDeltaPosition(this._tmpPositionVector);
};
OimoJSPlugin2.prototype.removePhysicsBody = function(impostor) {
this.world.removeRigidBody(impostor.physicsBody);
};
OimoJSPlugin2.prototype.generateJoint = function(impostorJoint) {
var mainBody = impostorJoint.mainImpostor.physicsBody;
var connectedBody = impostorJoint.connectedImpostor.physicsBody;
if (!mainBody || !connectedBody) {
return;
}
var jointData = impostorJoint.joint.jointData;
var options = jointData.nativeParams || {};
var type;
var nativeJointData = {
body1: mainBody,
body2: connectedBody,
axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
min: options.min,
max: options.max,
collision: options.collision || jointData.collision,
spring: options.spring,
//supporting older version of Oimo
world: this.world
};
switch (impostorJoint.joint.type) {
case BABYLON2.PhysicsJoint.BallAndSocketJoint:
type = "jointBall";
break;
case BABYLON2.PhysicsJoint.SpringJoint:
BABYLON2.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
var springData = jointData;
nativeJointData.min = springData.length || nativeJointData.min;
nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
case BABYLON2.PhysicsJoint.DistanceJoint:
type = "jointDistance";
nativeJointData.max = jointData.maxDistance;
break;
case BABYLON2.PhysicsJoint.PrismaticJoint:
type = "jointPrisme";
break;
case BABYLON2.PhysicsJoint.SliderJoint:
type = "jointSlide";
break;
case BABYLON2.PhysicsJoint.WheelJoint:
type = "jointWheel";
break;
case BABYLON2.PhysicsJoint.HingeJoint:
default:
type = "jointHinge";
break;
}
nativeJointData.type = type;
impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
};
OimoJSPlugin2.prototype.removeJoint = function(impostorJoint) {
try {
this.world.removeJoint(impostorJoint.joint.physicsJoint);
} catch (e2) {
BABYLON2.Tools.Warn(e2);
}
};
OimoJSPlugin2.prototype.isSupported = function() {
return this.BJSOIMO !== void 0;
};
OimoJSPlugin2.prototype.setTransformationFromPhysicsBody = function(impostor) {
if (!impostor.physicsBody.sleeping) {
impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
if (impostor.object.rotationQuaternion) {
impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
}
}
};
OimoJSPlugin2.prototype.setPhysicsBodyTransformation = function(impostor, newPosition, newRotation) {
var body = impostor.physicsBody;
body.position.copy(newPosition);
body.orientation.copy(newRotation);
body.syncShapes();
body.awake();
};
OimoJSPlugin2.prototype.setLinearVelocity = function(impostor, velocity) {
impostor.physicsBody.linearVelocity.copy(velocity);
};
OimoJSPlugin2.prototype.setAngularVelocity = function(impostor, velocity) {
impostor.physicsBody.angularVelocity.copy(velocity);
};
OimoJSPlugin2.prototype.getLinearVelocity = function(impostor) {
var v = impostor.physicsBody.linearVelocity;
if (!v) {
return null;
}
return new BABYLON2.Vector3(v.x, v.y, v.z);
};
OimoJSPlugin2.prototype.getAngularVelocity = function(impostor) {
var v = impostor.physicsBody.angularVelocity;
if (!v) {
return null;
}
return new BABYLON2.Vector3(v.x, v.y, v.z);
};
OimoJSPlugin2.prototype.setBodyMass = function(impostor, mass) {
var staticBody = mass === 0;
impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
impostor.physicsBody.setupMass(staticBody ? 2 : 1);
};
OimoJSPlugin2.prototype.getBodyMass = function(impostor) {
return impostor.physicsBody.shapes.density;
};
OimoJSPlugin2.prototype.getBodyFriction = function(impostor) {
return impostor.physicsBody.shapes.friction;
};
OimoJSPlugin2.prototype.setBodyFriction = function(impostor, friction) {
impostor.physicsBody.shapes.friction = friction;
};
OimoJSPlugin2.prototype.getBodyRestitution = function(impostor) {
return impostor.physicsBody.shapes.restitution;
};
OimoJSPlugin2.prototype.setBodyRestitution = function(impostor, restitution) {
impostor.physicsBody.shapes.restitution = restitution;
};
OimoJSPlugin2.prototype.sleepBody = function(impostor) {
impostor.physicsBody.sleep();
};
OimoJSPlugin2.prototype.wakeUpBody = function(impostor) {
impostor.physicsBody.awake();
};
OimoJSPlugin2.prototype.updateDistanceJoint = function(joint, maxDistance, minDistance) {
joint.physicsJoint.limitMotor.upperLimit = maxDistance;
if (minDistance !== void 0) {
joint.physicsJoint.limitMotor.lowerLimit = minDistance;
}
};
OimoJSPlugin2.prototype.setMotor = function(joint, speed, maxForce, motorIndex) {
var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
if (motor) {
motor.setMotor(speed, maxForce);
}
};
OimoJSPlugin2.prototype.setLimit = function(joint, upperLimit, lowerLimit, motorIndex) {
var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
if (motor) {
motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
}
};
OimoJSPlugin2.prototype.syncMeshWithImpostor = function(mesh2, impostor) {
var body = impostor.physicsBody;
mesh2.position.x = body.position.x;
mesh2.position.y = body.position.y;
mesh2.position.z = body.position.z;
if (mesh2.rotationQuaternion) {
mesh2.rotationQuaternion.x = body.orientation.x;
mesh2.rotationQuaternion.y = body.orientation.y;
mesh2.rotationQuaternion.z = body.orientation.z;
mesh2.rotationQuaternion.w = body.orientation.s;
}
};
OimoJSPlugin2.prototype.getRadius = function(impostor) {
return impostor.physicsBody.shapes.radius;
};
OimoJSPlugin2.prototype.getBoxSizeToRef = function(impostor, result) {
var shape = impostor.physicsBody.shapes;
result.x = shape.halfWidth * 2;
result.y = shape.halfHeight * 2;
result.z = shape.halfDepth * 2;
};
OimoJSPlugin2.prototype.dispose = function() {
this.world.clear();
};
return OimoJSPlugin2;
}()
);
BABYLON2.OimoJSPlugin = OimoJSPlugin;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Scene.prototype.getPhysicsEngine = function() {
return this._physicsEngine;
};
BABYLON2.Scene.prototype.enablePhysics = function(gravity, plugin) {
if (gravity === void 0) {
gravity = null;
}
if (this._physicsEngine) {
return true;
}
var component = this._getComponent(BABYLON2.SceneComponentConstants.NAME_PHYSICSENGINE);
if (!component) {
component = new PhysicsEngineSceneComponent(this);
this._addComponent(component);
}
try {
this._physicsEngine = new BABYLON2.PhysicsEngine(gravity, plugin);
return true;
} catch (e2) {
BABYLON2.Tools.Error(e2.message);
return false;
}
};
BABYLON2.Scene.prototype.disablePhysicsEngine = function() {
if (!this._physicsEngine) {
return;
}
this._physicsEngine.dispose();
this._physicsEngine = null;
};
BABYLON2.Scene.prototype.isPhysicsEnabled = function() {
return this._physicsEngine !== void 0;
};
BABYLON2.Scene.prototype.deleteCompoundImpostor = function(compound) {
var mesh2 = compound.parts[0].mesh;
if (mesh2.physicsImpostor) {
mesh2.physicsImpostor.dispose(
/*true*/
);
mesh2.physicsImpostor = null;
}
};
BABYLON2.Scene.prototype._advancePhysicsEngineStep = function(step) {
if (this._physicsEngine) {
this.onBeforePhysicsObservable.notifyObservers(this);
this._physicsEngine._step(step / 1e3);
this.onAfterPhysicsObservable.notifyObservers(this);
}
};
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "physicsImpostor", {
get: function() {
return this._physicsImpostor;
},
set: function(value) {
var _this = this;
if (this._physicsImpostor === value) {
return;
}
if (this._disposePhysicsObserver) {
this.onDisposeObservable.remove(this._disposePhysicsObserver);
}
this._physicsImpostor = value;
if (value) {
this._disposePhysicsObserver = this.onDisposeObservable.add(function() {
if (_this.physicsImpostor) {
_this.physicsImpostor.dispose(
/*!doNotRecurse*/
);
_this.physicsImpostor = null;
}
});
}
},
enumerable: true,
configurable: true
});
BABYLON2.AbstractMesh.prototype.getPhysicsImpostor = function() {
return this.physicsImpostor;
};
BABYLON2.AbstractMesh.prototype.applyImpulse = function(force, contactPoint) {
if (!this.physicsImpostor) {
return this;
}
this.physicsImpostor.applyImpulse(force, contactPoint);
return this;
};
BABYLON2.AbstractMesh.prototype.setPhysicsLinkWith = function(otherMesh, pivot1, pivot2, options) {
if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
return this;
}
this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON2.PhysicsJoint.HingeJoint, {
mainPivot: pivot1,
connectedPivot: pivot2,
nativeParams: options
});
return this;
};
var PhysicsEngineSceneComponent = (
/** @class */
function() {
function PhysicsEngineSceneComponent2(scene) {
var _this = this;
this.name = BABYLON2.SceneComponentConstants.NAME_PHYSICSENGINE;
this.scene = scene;
this.scene.onBeforePhysicsObservable = new BABYLON2.Observable();
this.scene.onAfterPhysicsObservable = new BABYLON2.Observable();
this.scene.getDeterministicFrameTime = function() {
if (_this.scene._physicsEngine) {
return _this.scene._physicsEngine.getTimeStep() * 1e3;
}
return 1e3 / 60;
};
}
PhysicsEngineSceneComponent2.prototype.register = function() {
};
PhysicsEngineSceneComponent2.prototype.rebuild = function() {
};
PhysicsEngineSceneComponent2.prototype.dispose = function() {
this.scene.onBeforePhysicsObservable.clear();
this.scene.onAfterPhysicsObservable.clear();
if (this.scene._physicsEngine) {
this.scene.disablePhysicsEngine();
}
};
return PhysicsEngineSceneComponent2;
}()
);
BABYLON2.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DDS_MAGIC = 542327876;
var DDSD_MIPMAPCOUNT = 131072;
var DDSCAPS2_CUBEMAP = 512;
var DDPF_FOURCC = 4, DDPF_RGB = 64, DDPF_LUMINANCE = 131072;
function FourCCToInt32(value) {
return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
}
function Int32ToFourCC(value) {
return String.fromCharCode(value & 255, value >> 8 & 255, value >> 16 & 255, value >> 24 & 255);
}
var FOURCC_DXT1 = FourCCToInt32("DXT1");
var FOURCC_DXT3 = FourCCToInt32("DXT3");
var FOURCC_DXT5 = FourCCToInt32("DXT5");
var FOURCC_DX10 = FourCCToInt32("DX10");
var FOURCC_D3DFMT_R16G16B16A16F = 113;
var FOURCC_D3DFMT_R32G32B32A32F = 116;
var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
var headerLengthInt = 31;
var off_magic = 0;
var off_size = 1;
var off_flags = 2;
var off_height = 3;
var off_width = 4;
var off_mipmapCount = 7;
var off_pfFlags = 20;
var off_pfFourCC = 21;
var off_RGBbpp = 22;
var off_RMask = 23;
var off_GMask = 24;
var off_BMask = 25;
var off_AMask = 26;
var off_caps2 = 28;
var off_dxgiFormat = 32;
var DDSTools = (
/** @class */
function() {
function DDSTools2() {
}
DDSTools2.GetDDSInfo = function(arrayBuffer) {
var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
var mipmapCount = 1;
if (header[off_flags] & DDSD_MIPMAPCOUNT) {
mipmapCount = Math.max(1, header[off_mipmapCount]);
}
var fourCC = header[off_pfFourCC];
var dxgiFormat = fourCC === FOURCC_DX10 ? extendedHeader[off_dxgiFormat] : 0;
var textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
switch (fourCC) {
case FOURCC_D3DFMT_R16G16B16A16F:
textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
break;
case FOURCC_D3DFMT_R32G32B32A32F:
textureType = BABYLON2.Engine.TEXTURETYPE_FLOAT;
break;
case FOURCC_DX10:
if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
break;
}
}
return {
width: header[off_width],
height: header[off_height],
mipmapCount,
isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
isCompressed: fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5,
dxgiFormat,
textureType
};
};
DDSTools2._ToHalfFloat = function(value) {
if (!DDSTools2._FloatView) {
DDSTools2._FloatView = new Float32Array(1);
DDSTools2._Int32View = new Int32Array(DDSTools2._FloatView.buffer);
}
DDSTools2._FloatView[0] = value;
var x = DDSTools2._Int32View[0];
var bits = x >> 16 & 32768;
var m = x >> 12 & 2047;
var e2 = x >> 23 & 255;
if (e2 < 103) {
return bits;
}
if (e2 > 142) {
bits |= 31744;
bits |= (e2 == 255 ? 0 : 1) && x & 8388607;
return bits;
}
if (e2 < 113) {
m |= 2048;
bits |= (m >> 114 - e2) + (m >> 113 - e2 & 1);
return bits;
}
bits |= e2 - 112 << 10 | m >> 1;
bits += m & 1;
return bits;
};
DDSTools2._FromHalfFloat = function(value) {
var s = (value & 32768) >> 15;
var e2 = (value & 31744) >> 10;
var f = value & 1023;
if (e2 === 0) {
return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
} else if (e2 == 31) {
return f ? NaN : (s ? -1 : 1) * Infinity;
}
return (s ? -1 : 1) * Math.pow(2, e2 - 15) * (1 + f / Math.pow(2, 10));
};
DDSTools2._GetHalfFloatAsFloatRGBAArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer, lod) {
var destArray = new Float32Array(dataLength);
var srcData = new Uint16Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = (x + y * width) * 4;
destArray[index] = DDSTools2._FromHalfFloat(srcData[srcPos]);
destArray[index + 1] = DDSTools2._FromHalfFloat(srcData[srcPos + 1]);
destArray[index + 2] = DDSTools2._FromHalfFloat(srcData[srcPos + 2]);
if (DDSTools2.StoreLODInAlphaChannel) {
destArray[index + 3] = lod;
} else {
destArray[index + 3] = DDSTools2._FromHalfFloat(srcData[srcPos + 3]);
}
index += 4;
}
}
return destArray;
};
DDSTools2._GetHalfFloatRGBAArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer, lod) {
if (DDSTools2.StoreLODInAlphaChannel) {
var destArray = new Uint16Array(dataLength);
var srcData = new Uint16Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = (x + y * width) * 4;
destArray[index] = srcData[srcPos];
destArray[index + 1] = srcData[srcPos + 1];
destArray[index + 2] = srcData[srcPos + 2];
destArray[index + 3] = DDSTools2._ToHalfFloat(lod);
index += 4;
}
}
return destArray;
}
return new Uint16Array(arrayBuffer, dataOffset, dataLength);
};
DDSTools2._GetFloatRGBAArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer, lod) {
if (DDSTools2.StoreLODInAlphaChannel) {
var destArray = new Float32Array(dataLength);
var srcData = new Float32Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = (x + y * width) * 4;
destArray[index] = srcData[srcPos];
destArray[index + 1] = srcData[srcPos + 1];
destArray[index + 2] = srcData[srcPos + 2];
destArray[index + 3] = lod;
index += 4;
}
}
return destArray;
}
return new Float32Array(arrayBuffer, dataOffset, dataLength);
};
DDSTools2._GetFloatAsUIntRGBAArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer, lod) {
var destArray = new Uint8Array(dataLength);
var srcData = new Float32Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = (x + y * width) * 4;
destArray[index] = BABYLON2.Scalar.Clamp(srcData[srcPos]) * 255;
destArray[index + 1] = BABYLON2.Scalar.Clamp(srcData[srcPos + 1]) * 255;
destArray[index + 2] = BABYLON2.Scalar.Clamp(srcData[srcPos + 2]) * 255;
if (DDSTools2.StoreLODInAlphaChannel) {
destArray[index + 3] = lod;
} else {
destArray[index + 3] = BABYLON2.Scalar.Clamp(srcData[srcPos + 3]) * 255;
}
index += 4;
}
}
return destArray;
};
DDSTools2._GetHalfFloatAsUIntRGBAArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer, lod) {
var destArray = new Uint8Array(dataLength);
var srcData = new Uint16Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = (x + y * width) * 4;
destArray[index] = BABYLON2.Scalar.Clamp(DDSTools2._FromHalfFloat(srcData[srcPos])) * 255;
destArray[index + 1] = BABYLON2.Scalar.Clamp(DDSTools2._FromHalfFloat(srcData[srcPos + 1])) * 255;
destArray[index + 2] = BABYLON2.Scalar.Clamp(DDSTools2._FromHalfFloat(srcData[srcPos + 2])) * 255;
if (DDSTools2.StoreLODInAlphaChannel) {
destArray[index + 3] = lod;
} else {
destArray[index + 3] = BABYLON2.Scalar.Clamp(DDSTools2._FromHalfFloat(srcData[srcPos + 3])) * 255;
}
index += 4;
}
}
return destArray;
};
DDSTools2._GetRGBAArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
var byteArray = new Uint8Array(dataLength);
var srcData = new Uint8Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = (x + y * width) * 4;
byteArray[index] = srcData[srcPos + rOffset];
byteArray[index + 1] = srcData[srcPos + gOffset];
byteArray[index + 2] = srcData[srcPos + bOffset];
byteArray[index + 3] = srcData[srcPos + aOffset];
index += 4;
}
}
return byteArray;
};
DDSTools2._ExtractLongWordOrder = function(value) {
if (value === 0 || value === 255 || value === -16777216) {
return 0;
}
return 1 + DDSTools2._ExtractLongWordOrder(value >> 8);
};
DDSTools2._GetRGBArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
var byteArray = new Uint8Array(dataLength);
var srcData = new Uint8Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = (x + y * width) * 3;
byteArray[index] = srcData[srcPos + rOffset];
byteArray[index + 1] = srcData[srcPos + gOffset];
byteArray[index + 2] = srcData[srcPos + bOffset];
index += 3;
}
}
return byteArray;
};
DDSTools2._GetLuminanceArrayBuffer = function(width, height, dataOffset, dataLength, arrayBuffer) {
var byteArray = new Uint8Array(dataLength);
var srcData = new Uint8Array(arrayBuffer, dataOffset);
var index = 0;
for (var y = 0; y < height; y++) {
for (var x = 0; x < width; x++) {
var srcPos = x + y * width;
byteArray[index] = srcData[srcPos];
index++;
}
}
return byteArray;
};
DDSTools2.UploadDDSLevels = function(engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
if (lodIndex === void 0) {
lodIndex = -1;
}
var sphericalPolynomialFaces = null;
if (info.sphericalPolynomial) {
sphericalPolynomialFaces = new Array();
}
var ext = engine.getCaps().s3tc;
var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
var fourCC, width, height, dataLength = 0, dataOffset;
var byteArray, mipmapCount, mip;
var internalCompressedFormat = 0;
var blockBytes = 1;
if (header[off_magic] !== DDS_MAGIC) {
BABYLON2.Tools.Error("Invalid magic number in DDS header");
return;
}
if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
BABYLON2.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
return;
}
if (info.isCompressed && !ext) {
BABYLON2.Tools.Error("Compressed textures are not supported on this platform.");
return;
}
var bpp = header[off_RGBbpp];
dataOffset = header[off_size] + 4;
var computeFormats = false;
if (info.isFourCC) {
fourCC = header[off_pfFourCC];
switch (fourCC) {
case FOURCC_DXT1:
blockBytes = 8;
internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
break;
case FOURCC_DXT3:
blockBytes = 16;
internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
break;
case FOURCC_DXT5:
blockBytes = 16;
internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
break;
case FOURCC_D3DFMT_R16G16B16A16F:
computeFormats = true;
break;
case FOURCC_D3DFMT_R32G32B32A32F:
computeFormats = true;
break;
case FOURCC_DX10:
dataOffset += 5 * 4;
var supported = false;
switch (info.dxgiFormat) {
case DXGI_FORMAT_R16G16B16A16_FLOAT:
computeFormats = true;
supported = true;
break;
case DXGI_FORMAT_B8G8R8X8_UNORM:
info.isRGB = true;
info.isFourCC = false;
bpp = 32;
supported = true;
break;
}
if (supported) {
break;
}
default:
console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
return;
}
}
var rOffset = DDSTools2._ExtractLongWordOrder(header[off_RMask]);
var gOffset = DDSTools2._ExtractLongWordOrder(header[off_GMask]);
var bOffset = DDSTools2._ExtractLongWordOrder(header[off_BMask]);
var aOffset = DDSTools2._ExtractLongWordOrder(header[off_AMask]);
if (computeFormats) {
internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
}
mipmapCount = 1;
if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
mipmapCount = Math.max(1, header[off_mipmapCount]);
}
for (var face = 0; face < faces; face++) {
width = header[off_width];
height = header[off_height];
for (mip = 0; mip < mipmapCount; ++mip) {
if (lodIndex === -1 || lodIndex === mip) {
var i2 = lodIndex === -1 ? mip : 0;
if (!info.isCompressed && info.isFourCC) {
texture.format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
dataLength = width * height * 4;
var floatArray = null;
if (engine._badOS || engine._badDesktopOS || !engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat) {
if (bpp === 128) {
floatArray = DDSTools2._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2);
if (sphericalPolynomialFaces && i2 == 0) {
sphericalPolynomialFaces.push(DDSTools2._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2));
}
} else if (bpp === 64) {
floatArray = DDSTools2._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2);
if (sphericalPolynomialFaces && i2 == 0) {
sphericalPolynomialFaces.push(DDSTools2._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2));
}
}
texture.type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
} else {
if (bpp === 128) {
texture.type = BABYLON2.Engine.TEXTURETYPE_FLOAT;
floatArray = DDSTools2._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2);
if (sphericalPolynomialFaces && i2 == 0) {
sphericalPolynomialFaces.push(floatArray);
}
} else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
texture.type = BABYLON2.Engine.TEXTURETYPE_FLOAT;
floatArray = DDSTools2._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2);
if (sphericalPolynomialFaces && i2 == 0) {
sphericalPolynomialFaces.push(floatArray);
}
} else {
texture.type = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
floatArray = DDSTools2._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2);
if (sphericalPolynomialFaces && i2 == 0) {
sphericalPolynomialFaces.push(DDSTools2._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i2));
}
}
}
if (floatArray) {
engine._uploadDataToTextureDirectly(texture, floatArray, face, i2);
}
} else if (info.isRGB) {
texture.type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
if (bpp === 24) {
texture.format = BABYLON2.Engine.TEXTUREFORMAT_RGB;
dataLength = width * height * 3;
byteArray = DDSTools2._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
engine._uploadDataToTextureDirectly(texture, byteArray, face, i2);
} else {
texture.format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
dataLength = width * height * 4;
byteArray = DDSTools2._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
engine._uploadDataToTextureDirectly(texture, byteArray, face, i2);
}
} else if (info.isLuminance) {
var unpackAlignment = engine._getUnpackAlignement();
var unpaddedRowSize = width;
var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
byteArray = DDSTools2._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
texture.format = BABYLON2.Engine.TEXTUREFORMAT_LUMINANCE;
texture.type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
engine._uploadDataToTextureDirectly(texture, byteArray, face, i2);
} else {
dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
texture.type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i2);
}
}
dataOffset += bpp ? width * height * (bpp / 8) : dataLength;
width *= 0.5;
height *= 0.5;
width = Math.max(1, width);
height = Math.max(1, height);
}
if (currentFace !== void 0) {
break;
}
}
if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
info.sphericalPolynomial = BABYLON2.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
size: header[off_width],
right: sphericalPolynomialFaces[0],
left: sphericalPolynomialFaces[1],
up: sphericalPolynomialFaces[2],
down: sphericalPolynomialFaces[3],
front: sphericalPolynomialFaces[4],
back: sphericalPolynomialFaces[5],
format: BABYLON2.Engine.TEXTUREFORMAT_RGBA,
type: BABYLON2.Engine.TEXTURETYPE_FLOAT,
gammaSpace: false
});
} else {
info.sphericalPolynomial = void 0;
}
};
DDSTools2.StoreLODInAlphaChannel = false;
return DDSTools2;
}()
);
BABYLON2.DDSTools = DDSTools;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var DDSTextureLoader = (
/** @class */
function() {
function DDSTextureLoader2() {
this.supportCascades = true;
}
DDSTextureLoader2.prototype.canLoad = function(extension, textureFormatInUse, fallback, isBase64, isBuffer) {
return extension.indexOf(".dds") === 0;
};
DDSTextureLoader2.prototype.transformUrl = function(rootUrl, textureFormatInUse) {
return rootUrl;
};
DDSTextureLoader2.prototype.getFallbackTextureUrl = function(rootUrl, textureFormatInUse) {
return null;
};
DDSTextureLoader2.prototype.loadCubeData = function(imgs, texture, createPolynomials, onLoad, onError) {
var engine = texture.getEngine();
var info;
var loadMipmap = false;
if (Array.isArray(imgs)) {
for (var index = 0; index < imgs.length; index++) {
var data_1 = imgs[index];
info = BABYLON2.DDSTools.GetDDSInfo(data_1);
texture.width = info.width;
texture.height = info.height;
loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
engine._unpackFlipY(info.isCompressed);
BABYLON2.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
if (!info.isFourCC && info.mipmapCount === 1) {
engine.generateMipMapsForCubemap(texture);
}
}
} else {
var data2 = imgs;
info = BABYLON2.DDSTools.GetDDSInfo(data2);
texture.width = info.width;
texture.height = info.height;
if (createPolynomials) {
info.sphericalPolynomial = new BABYLON2.SphericalPolynomial();
}
loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
engine._unpackFlipY(info.isCompressed);
BABYLON2.DDSTools.UploadDDSLevels(engine, texture, data2, info, loadMipmap, 6);
if (!info.isFourCC && info.mipmapCount === 1) {
engine.generateMipMapsForCubemap(texture);
}
}
engine._setCubeMapTextureParams(loadMipmap);
texture.isReady = true;
if (onLoad) {
onLoad({ isDDS: true, width: texture.width, info, data: imgs, texture });
}
};
DDSTextureLoader2.prototype.loadData = function(data2, texture, callback) {
var info = BABYLON2.DDSTools.GetDDSInfo(data2);
var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && info.width >> info.mipmapCount - 1 === 1;
callback(info.width, info.height, loadMipmap, info.isFourCC, function() {
BABYLON2.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data2, info, loadMipmap, 1);
});
};
return DDSTextureLoader2;
}()
);
BABYLON2.Engine._TextureLoaders.push(new DDSTextureLoader());
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var TGATools = (
/** @class */
function() {
function TGATools2() {
}
TGATools2.GetTGAHeader = function(data2) {
var offset = 0;
var header = {
id_length: data2[offset++],
colormap_type: data2[offset++],
image_type: data2[offset++],
colormap_index: data2[offset++] | data2[offset++] << 8,
colormap_length: data2[offset++] | data2[offset++] << 8,
colormap_size: data2[offset++],
origin: [
data2[offset++] | data2[offset++] << 8,
data2[offset++] | data2[offset++] << 8
],
width: data2[offset++] | data2[offset++] << 8,
height: data2[offset++] | data2[offset++] << 8,
pixel_size: data2[offset++],
flags: data2[offset++]
};
return header;
};
TGATools2.UploadContent = function(texture, data2) {
if (data2.length < 19) {
BABYLON2.Tools.Error("Unable to load TGA file - Not enough data to contain header");
return;
}
var offset = 18;
var header = TGATools2.GetTGAHeader(data2);
if (header.id_length + offset > data2.length) {
BABYLON2.Tools.Error("Unable to load TGA file - Not enough data");
return;
}
offset += header.id_length;
var use_rle = false;
var use_pal = false;
var use_grey = false;
switch (header.image_type) {
case TGATools2._TYPE_RLE_INDEXED:
use_rle = true;
case TGATools2._TYPE_INDEXED:
use_pal = true;
break;
case TGATools2._TYPE_RLE_RGB:
use_rle = true;
case TGATools2._TYPE_RGB:
break;
case TGATools2._TYPE_RLE_GREY:
use_rle = true;
case TGATools2._TYPE_GREY:
use_grey = true;
break;
}
var pixel_data;
var pixel_size = header.pixel_size >> 3;
var pixel_total = header.width * header.height * pixel_size;
var palettes;
if (use_pal) {
palettes = data2.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
}
if (use_rle) {
pixel_data = new Uint8Array(pixel_total);
var c, count, i2;
var localOffset = 0;
var pixels = new Uint8Array(pixel_size);
while (offset < pixel_total && localOffset < pixel_total) {
c = data2[offset++];
count = (c & 127) + 1;
if (c & 128) {
for (i2 = 0; i2 < pixel_size; ++i2) {
pixels[i2] = data2[offset++];
}
for (i2 = 0; i2 < count; ++i2) {
pixel_data.set(pixels, localOffset + i2 * pixel_size);
}
localOffset += pixel_size * count;
} else {
count *= pixel_size;
for (i2 = 0; i2 < count; ++i2) {
pixel_data[localOffset + i2] = data2[offset++];
}
localOffset += count;
}
}
} else {
pixel_data = data2.subarray(offset, offset += use_pal ? header.width * header.height : pixel_total);
}
var x_start, y_start, x_step, y_step, y_end, x_end;
switch ((header.flags & TGATools2._ORIGIN_MASK) >> TGATools2._ORIGIN_SHIFT) {
default:
case TGATools2._ORIGIN_UL:
x_start = 0;
x_step = 1;
x_end = header.width;
y_start = 0;
y_step = 1;
y_end = header.height;
break;
case TGATools2._ORIGIN_BL:
x_start = 0;
x_step = 1;
x_end = header.width;
y_start = header.height - 1;
y_step = -1;
y_end = -1;
break;
case TGATools2._ORIGIN_UR:
x_start = header.width - 1;
x_step = -1;
x_end = -1;
y_start = 0;
y_step = 1;
y_end = header.height;
break;
case TGATools2._ORIGIN_BR:
x_start = header.width - 1;
x_step = -1;
x_end = -1;
y_start = header.height - 1;
y_step = -1;
y_end = -1;
break;
}
var func = "_getImageData" + (use_grey ? "Grey" : "") + header.pixel_size + "bits";
var imageData = TGATools2[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
var engine = texture.getEngine();
engine._uploadDataToTextureDirectly(texture, imageData);
};
TGATools2._getImageData8bits = function(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
var image = pixel_data, colormap = palettes;
var width = header.width, height = header.height;
var color, i2 = 0, x, y;
var imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i2++) {
color = image[i2];
imageData[(x + width * y) * 4 + 3] = 255;
imageData[(x + width * y) * 4 + 2] = colormap[color * 3 + 0];
imageData[(x + width * y) * 4 + 1] = colormap[color * 3 + 1];
imageData[(x + width * y) * 4 + 0] = colormap[color * 3 + 2];
}
}
return imageData;
};
TGATools2._getImageData16bits = function(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
var image = pixel_data;
var width = header.width, height = header.height;
var color, i2 = 0, x, y;
var imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i2 += 2) {
color = image[i2 + 0] + (image[i2 + 1] << 8);
var r = ((color & 31744) >> 10) * 255 / 31 | 0;
var g = ((color & 992) >> 5) * 255 / 31 | 0;
var b2 = (color & 31) * 255 / 31 | 0;
imageData[(x + width * y) * 4 + 0] = r;
imageData[(x + width * y) * 4 + 1] = g;
imageData[(x + width * y) * 4 + 2] = b2;
imageData[(x + width * y) * 4 + 3] = color & 32768 ? 0 : 255;
}
}
return imageData;
};
TGATools2._getImageData24bits = function(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
var image = pixel_data;
var width = header.width, height = header.height;
var i2 = 0, x, y;
var imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i2 += 3) {
imageData[(x + width * y) * 4 + 3] = 255;
imageData[(x + width * y) * 4 + 2] = image[i2 + 0];
imageData[(x + width * y) * 4 + 1] = image[i2 + 1];
imageData[(x + width * y) * 4 + 0] = image[i2 + 2];
}
}
return imageData;
};
TGATools2._getImageData32bits = function(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
var image = pixel_data;
var width = header.width, height = header.height;
var i2 = 0, x, y;
var imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i2 += 4) {
imageData[(x + width * y) * 4 + 2] = image[i2 + 0];
imageData[(x + width * y) * 4 + 1] = image[i2 + 1];
imageData[(x + width * y) * 4 + 0] = image[i2 + 2];
imageData[(x + width * y) * 4 + 3] = image[i2 + 3];
}
}
return imageData;
};
TGATools2._getImageDataGrey8bits = function(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
var image = pixel_data;
var width = header.width, height = header.height;
var color, i2 = 0, x, y;
var imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i2++) {
color = image[i2];
imageData[(x + width * y) * 4 + 0] = color;
imageData[(x + width * y) * 4 + 1] = color;
imageData[(x + width * y) * 4 + 2] = color;
imageData[(x + width * y) * 4 + 3] = 255;
}
}
return imageData;
};
TGATools2._getImageDataGrey16bits = function(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
var image = pixel_data;
var width = header.width, height = header.height;
var i2 = 0, x, y;
var imageData = new Uint8Array(width * height * 4);
for (y = y_start; y !== y_end; y += y_step) {
for (x = x_start; x !== x_end; x += x_step, i2 += 2) {
imageData[(x + width * y) * 4 + 0] = image[i2 + 0];
imageData[(x + width * y) * 4 + 1] = image[i2 + 0];
imageData[(x + width * y) * 4 + 2] = image[i2 + 0];
imageData[(x + width * y) * 4 + 3] = image[i2 + 1];
}
}
return imageData;
};
TGATools2._TYPE_INDEXED = 1;
TGATools2._TYPE_RGB = 2;
TGATools2._TYPE_GREY = 3;
TGATools2._TYPE_RLE_INDEXED = 9;
TGATools2._TYPE_RLE_RGB = 10;
TGATools2._TYPE_RLE_GREY = 11;
TGATools2._ORIGIN_MASK = 48;
TGATools2._ORIGIN_SHIFT = 4;
TGATools2._ORIGIN_BL = 0;
TGATools2._ORIGIN_BR = 1;
TGATools2._ORIGIN_UL = 2;
TGATools2._ORIGIN_UR = 3;
return TGATools2;
}()
);
BABYLON2.TGATools = TGATools;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var TGATextureLoader = (
/** @class */
function() {
function TGATextureLoader2() {
this.supportCascades = false;
}
TGATextureLoader2.prototype.canLoad = function(extension, textureFormatInUse, fallback, isBase64, isBuffer) {
return extension.indexOf(".tga") === 0;
};
TGATextureLoader2.prototype.transformUrl = function(rootUrl, textureFormatInUse) {
return rootUrl;
};
TGATextureLoader2.prototype.getFallbackTextureUrl = function(rootUrl, textureFormatInUse) {
return null;
};
TGATextureLoader2.prototype.loadCubeData = function(data2, texture, createPolynomials, onLoad, onError) {
throw ".env not supported in Cube.";
};
TGATextureLoader2.prototype.loadData = function(data2, texture, callback) {
var uintData = new Uint8Array(data2);
var header = BABYLON2.TGATools.GetTGAHeader(uintData);
callback(header.width, header.height, texture.generateMipMaps, false, function() {
BABYLON2.TGATools.UploadContent(texture, uintData);
});
};
return TGATextureLoader2;
}()
);
BABYLON2.Engine._TextureLoaders.push(new TGATextureLoader());
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var KhronosTextureContainer = (
/** @class */
function() {
function KhronosTextureContainer2(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
this.arrayBuffer = arrayBuffer;
var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
if (identifier[0] !== 171 || identifier[1] !== 75 || identifier[2] !== 84 || identifier[3] !== 88 || identifier[4] !== 32 || identifier[5] !== 49 || identifier[6] !== 49 || identifier[7] !== 187 || identifier[8] !== 13 || identifier[9] !== 10 || identifier[10] !== 26 || identifier[11] !== 10) {
BABYLON2.Tools.Error("texture missing KTX identifier");
return;
}
var header = new Int32Array(this.arrayBuffer, 12, 13);
var oppositeEndianess = header[0] === 16909060;
this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1];
this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2];
this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3];
this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4];
this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5];
this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6];
this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7];
this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8];
this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9];
this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10];
this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11];
this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12];
if (this.glType !== 0) {
BABYLON2.Tools.Error("only compressed formats currently supported");
return;
} else {
this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
}
if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
BABYLON2.Tools.Error("only 2D textures currently supported");
return;
}
if (this.numberOfArrayElements !== 0) {
BABYLON2.Tools.Error("texture arrays not currently supported");
return;
}
if (this.numberOfFaces !== facesExpected) {
BABYLON2.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
return;
}
this.loadType = KhronosTextureContainer2.COMPRESSED_2D;
}
KhronosTextureContainer2.prototype.switchEndianness = function(val) {
return (val & 255) << 24 | (val & 65280) << 8 | val >> 8 & 65280 | val >> 24 & 255;
};
KhronosTextureContainer2.prototype.uploadLevels = function(texture, loadMipmaps) {
switch (this.loadType) {
case KhronosTextureContainer2.COMPRESSED_2D:
this._upload2DCompressedLevels(texture, loadMipmaps);
break;
case KhronosTextureContainer2.TEX_2D:
case KhronosTextureContainer2.COMPRESSED_3D:
case KhronosTextureContainer2.TEX_3D:
}
};
KhronosTextureContainer2.prototype._upload2DCompressedLevels = function(texture, loadMipmaps) {
var dataOffset = KhronosTextureContainer2.HEADER_LEN + this.bytesOfKeyValueData;
var width = this.pixelWidth;
var height = this.pixelHeight;
var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
for (var level = 0; level < mipmapCount; level++) {
var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0];
dataOffset += 4;
for (var face = 0; face < this.numberOfFaces; face++) {
var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
var engine = texture.getEngine();
engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
dataOffset += imageSize;
dataOffset += 3 - (imageSize + 3) % 4;
}
width = Math.max(1, width * 0.5);
height = Math.max(1, height * 0.5);
}
};
KhronosTextureContainer2.HEADER_LEN = 12 + 13 * 4;
KhronosTextureContainer2.COMPRESSED_2D = 0;
KhronosTextureContainer2.COMPRESSED_3D = 1;
KhronosTextureContainer2.TEX_2D = 2;
KhronosTextureContainer2.TEX_3D = 3;
return KhronosTextureContainer2;
}()
);
BABYLON2.KhronosTextureContainer = KhronosTextureContainer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var KTXTextureLoader = (
/** @class */
function() {
function KTXTextureLoader2() {
this.supportCascades = false;
}
KTXTextureLoader2.prototype.canLoad = function(extension, textureFormatInUse, fallback, isBase64, isBuffer) {
if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
return true;
}
return false;
};
KTXTextureLoader2.prototype.transformUrl = function(rootUrl, textureFormatInUse) {
var lastDot = rootUrl.lastIndexOf(".");
return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
};
KTXTextureLoader2.prototype.getFallbackTextureUrl = function(rootUrl, textureFormatInUse) {
var exp = new RegExp("" + textureFormatInUse + "$");
return rootUrl.replace(exp, "");
};
KTXTextureLoader2.prototype.loadCubeData = function(data2, texture, createPolynomials, onLoad, onError) {
if (Array.isArray(data2)) {
return;
}
var engine = texture.getEngine();
var ktx = new BABYLON2.KhronosTextureContainer(data2, 6);
var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
engine._unpackFlipY(true);
ktx.uploadLevels(texture, texture.generateMipMaps);
texture.width = ktx.pixelWidth;
texture.height = ktx.pixelHeight;
engine._setCubeMapTextureParams(loadMipmap);
texture.isReady = true;
};
KTXTextureLoader2.prototype.loadData = function(data2, texture, callback) {
var ktx = new BABYLON2.KhronosTextureContainer(data2, 1);
callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function() {
ktx.uploadLevels(texture, texture.generateMipMaps);
});
};
return KTXTextureLoader2;
}()
);
BABYLON2.Engine._TextureLoaders.unshift(new KTXTextureLoader());
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var EnvironmentTextureTools = (
/** @class */
function() {
function EnvironmentTextureTools2() {
}
EnvironmentTextureTools2.GetEnvInfo = function(data2) {
var dataView = new DataView(data2);
var pos = 0;
for (var i2 = 0; i2 < EnvironmentTextureTools2._MagicBytes.length; i2++) {
if (dataView.getUint8(pos++) !== EnvironmentTextureTools2._MagicBytes[i2]) {
BABYLON2.Tools.Error("Not a babylon environment map");
return null;
}
}
var manifestString = "";
var charCode = 0;
while (charCode = dataView.getUint8(pos++)) {
manifestString += String.fromCharCode(charCode);
}
var manifest = JSON.parse(manifestString);
if (manifest.specular) {
manifest.specular.specularDataPosition = pos;
manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
}
return manifest;
};
EnvironmentTextureTools2.CreateEnvTextureAsync = function(texture) {
var _this = this;
var internalTexture = texture.getInternalTexture();
if (!internalTexture) {
return Promise.reject("The cube texture is invalid.");
}
if (!texture._prefiltered) {
return Promise.reject("The cube texture is invalid (not prefiltered).");
}
var engine = internalTexture.getEngine();
if (engine && engine.premultipliedAlpha) {
return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
}
if (texture.textureType === BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT) {
return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
}
var canvas2 = engine.getRenderingCanvas();
if (!canvas2) {
return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
}
var textureType = BABYLON2.Engine.TEXTURETYPE_FLOAT;
if (!engine.getCaps().textureFloatRender) {
textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
if (!engine.getCaps().textureHalfFloatRender) {
return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
}
}
var cubeWidth = internalTexture.width;
var hostingScene = new BABYLON2.Scene(engine);
var specularTextures = {};
var promises = [];
var mipmapsCount = BABYLON2.Scalar.Log2(internalTexture.width);
mipmapsCount = Math.round(mipmapsCount);
var _loop_1 = function(i3) {
var faceWidth = Math.pow(2, mipmapsCount - i3);
var _loop_2 = function(face2) {
var data2 = texture.readPixels(face2, i3);
var tempTexture = engine.createRawTexture(data2, faceWidth, faceWidth, BABYLON2.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON2.Texture.NEAREST_SAMPLINGMODE, null, textureType);
var promise = new Promise(function(resolve, reject) {
var rgbdPostProcess = new BABYLON2.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON2.Texture.NEAREST_SAMPLINGMODE, engine, false, void 0, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT, void 0, null, false);
rgbdPostProcess.getEffect().executeWhenCompiled(function() {
rgbdPostProcess.onApply = function(effect) {
effect._bindTexture("textureSampler", tempTexture);
};
var currentW = engine.getRenderWidth();
var currentH = engine.getRenderHeight();
engine.setSize(faceWidth, faceWidth);
hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
BABYLON2.Tools.ToBlob(canvas2, function(blob2) {
var fileReader = new FileReader();
fileReader.onload = function(event) {
var arrayBuffer = event.target.result;
specularTextures[i3 * 6 + face2] = arrayBuffer;
resolve();
};
fileReader.readAsArrayBuffer(blob2);
});
engine.setSize(currentW, currentH);
});
});
promises.push(promise);
};
for (var face = 0; face < 6; face++) {
_loop_2(face);
}
};
for (var i2 = 0; i2 <= mipmapsCount; i2++) {
_loop_1(i2);
}
return Promise.all(promises).then(function() {
hostingScene.dispose();
var info = {
version: 1,
width: cubeWidth,
irradiance: _this._CreateEnvTextureIrradiance(texture),
specular: {
mipmaps: [],
lodGenerationScale: texture.lodGenerationScale
}
};
var position = 0;
for (var i3 = 0; i3 <= mipmapsCount; i3++) {
for (var face = 0; face < 6; face++) {
var byteLength = specularTextures[i3 * 6 + face].byteLength;
info.specular.mipmaps.push({
length: byteLength,
position
});
position += byteLength;
}
}
var infoString = JSON.stringify(info);
var infoBuffer = new ArrayBuffer(infoString.length + 1);
var infoView = new Uint8Array(infoBuffer);
for (var i3 = 0, strLen = infoString.length; i3 < strLen; i3++) {
infoView[i3] = infoString.charCodeAt(i3);
}
infoView[infoString.length] = 0;
var totalSize = EnvironmentTextureTools2._MagicBytes.length + position + infoBuffer.byteLength;
var finalBuffer = new ArrayBuffer(totalSize);
var finalBufferView = new Uint8Array(finalBuffer);
var dataView = new DataView(finalBuffer);
var pos = 0;
for (var i3 = 0; i3 < EnvironmentTextureTools2._MagicBytes.length; i3++) {
dataView.setUint8(pos++, EnvironmentTextureTools2._MagicBytes[i3]);
}
finalBufferView.set(new Uint8Array(infoBuffer), pos);
pos += infoBuffer.byteLength;
for (var i3 = 0; i3 <= mipmapsCount; i3++) {
for (var face = 0; face < 6; face++) {
var dataBuffer = specularTextures[i3 * 6 + face];
finalBufferView.set(new Uint8Array(dataBuffer), pos);
pos += dataBuffer.byteLength;
}
}
return finalBuffer;
});
};
EnvironmentTextureTools2._CreateEnvTextureIrradiance = function(texture) {
var polynmials = texture.sphericalPolynomial;
if (polynmials == null) {
return null;
}
return {
x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
};
};
EnvironmentTextureTools2.UploadEnvLevelsAsync = function(texture, arrayBuffer, info) {
if (info.version !== 1) {
throw new Error('Unsupported babylon environment map version "' + info.version + '"');
}
var specularInfo = info.specular;
if (!specularInfo) {
return Promise.resolve();
}
var mipmapsCount = BABYLON2.Scalar.Log2(info.width);
mipmapsCount = Math.round(mipmapsCount) + 1;
if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
throw new Error('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
}
texture._lodGenerationScale = specularInfo.lodGenerationScale;
var imageData = new Array(mipmapsCount);
for (var i2 = 0; i2 < mipmapsCount; i2++) {
imageData[i2] = new Array(6);
for (var face = 0; face < 6; face++) {
var imageInfo = specularInfo.mipmaps[i2 * 6 + face];
imageData[i2][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
}
}
return EnvironmentTextureTools2.UploadLevelsAsync(texture, imageData);
};
EnvironmentTextureTools2.UploadLevelsAsync = function(texture, imageData) {
if (!BABYLON2.Tools.IsExponentOfTwo(texture.width)) {
throw new Error("Texture size must be a power of two");
}
var mipmapsCount = Math.round(BABYLON2.Scalar.Log2(texture.width)) + 1;
var engine = texture.getEngine();
var expandTexture = false;
var generateNonLODTextures = false;
var rgbdPostProcess = null;
var cubeRtt = null;
var lodTextures = null;
var caps = engine.getCaps();
texture.format = BABYLON2.Engine.TEXTUREFORMAT_RGBA;
texture.type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
texture.generateMipMaps = true;
engine.updateTextureSamplingMode(BABYLON2.Texture.TRILINEAR_SAMPLINGMODE, texture);
if (!caps.textureLOD) {
expandTexture = false;
generateNonLODTextures = true;
lodTextures = {};
} else if (engine.webGLVersion < 2) {
expandTexture = false;
} else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
expandTexture = true;
texture.type = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
} else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
expandTexture = true;
texture.type = BABYLON2.Engine.TEXTURETYPE_FLOAT;
}
if (expandTexture) {
rgbdPostProcess = new BABYLON2.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON2.Texture.TRILINEAR_SAMPLINGMODE, engine, false, void 0, texture.type, void 0, null, false);
texture._isRGBD = false;
texture.invertY = false;
cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
generateDepthBuffer: false,
generateMipMaps: true,
generateStencilBuffer: false,
samplingMode: BABYLON2.Texture.TRILINEAR_SAMPLINGMODE,
type: texture.type,
format: BABYLON2.Engine.TEXTUREFORMAT_RGBA
});
} else {
texture._isRGBD = true;
texture.invertY = true;
if (generateNonLODTextures) {
var mipSlices = 3;
var scale = texture._lodGenerationScale;
var offset = texture._lodGenerationOffset;
for (var i2 = 0; i2 < mipSlices; i2++) {
var smoothness = i2 / (mipSlices - 1);
var roughness = 1 - smoothness;
var minLODIndex = offset;
var maxLODIndex = (mipmapsCount - 1) * scale + offset;
var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
var glTextureFromLod = new BABYLON2.InternalTexture(engine, BABYLON2.InternalTexture.DATASOURCE_TEMP);
glTextureFromLod.isCube = true;
glTextureFromLod.invertY = true;
glTextureFromLod.generateMipMaps = false;
engine.updateTextureSamplingMode(BABYLON2.Texture.LINEAR_LINEAR, glTextureFromLod);
var lodTexture = new BABYLON2.BaseTexture(null);
lodTexture.isCube = true;
lodTexture._texture = glTextureFromLod;
lodTextures[mipmapIndex] = lodTexture;
switch (i2) {
case 0:
texture._lodTextureLow = lodTexture;
break;
case 1:
texture._lodTextureMid = lodTexture;
break;
case 2:
texture._lodTextureHigh = lodTexture;
break;
}
}
}
}
var promises = [];
var _loop_3 = function(i3) {
var _loop_4 = function(face3) {
var bytes = imageData[i3][face3];
var blob2 = new Blob([bytes], { type: "image/png" });
var url = URL.createObjectURL(blob2);
var image = new Image();
image.src = url;
var promise = new Promise(function(resolve, reject) {
image.onload = function() {
if (expandTexture) {
var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON2.Texture.NEAREST_SAMPLINGMODE, null, function(message) {
reject(message);
}, image);
rgbdPostProcess.getEffect().executeWhenCompiled(function() {
rgbdPostProcess.onApply = function(effect) {
effect._bindTexture("textureSampler", tempTexture_1);
effect.setFloat2("scale", 1, 1);
};
engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face3, i3);
engine.restoreDefaultFramebuffer();
tempTexture_1.dispose();
window.URL.revokeObjectURL(url);
resolve();
});
} else {
engine._uploadImageToTexture(texture, image, face3, i3);
if (generateNonLODTextures) {
var lodTexture2 = lodTextures[i3];
if (lodTexture2) {
engine._uploadImageToTexture(lodTexture2._texture, image, face3, 0);
}
}
resolve();
}
};
image.onerror = function(error) {
reject(error);
};
});
promises.push(promise);
};
for (var face2 = 0; face2 < 6; face2++) {
_loop_4(face2);
}
};
for (var i2 = 0; i2 < imageData.length; i2++) {
_loop_3(i2);
}
if (imageData.length < mipmapsCount) {
var data2 = void 0;
var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
var dataLength = size * size * 4;
switch (texture.type) {
case BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT: {
data2 = new Uint8Array(dataLength);
break;
}
case BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT: {
data2 = new Uint16Array(dataLength);
break;
}
case BABYLON2.Engine.TEXTURETYPE_FLOAT: {
data2 = new Float32Array(dataLength);
break;
}
}
for (var i2 = imageData.length; i2 < mipmapsCount; i2++) {
for (var face = 0; face < 6; face++) {
engine._uploadArrayBufferViewToTexture(texture, data2, face, i2);
}
}
}
return Promise.all(promises).then(function() {
if (cubeRtt) {
engine._releaseFramebufferObjects(cubeRtt);
cubeRtt._swapAndDie(texture);
}
if (rgbdPostProcess) {
rgbdPostProcess.dispose();
}
if (generateNonLODTextures) {
if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
texture._lodTextureHigh._texture.isReady = true;
}
if (texture._lodTextureMid && texture._lodTextureMid._texture) {
texture._lodTextureMid._texture.isReady = true;
}
if (texture._lodTextureLow && texture._lodTextureLow._texture) {
texture._lodTextureLow._texture.isReady = true;
}
}
});
};
EnvironmentTextureTools2.UploadEnvSpherical = function(texture, info) {
if (info.version !== 1) {
BABYLON2.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
}
var irradianceInfo = info.irradiance;
if (!irradianceInfo) {
return;
}
var sp = new BABYLON2.SphericalPolynomial();
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
BABYLON2.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
texture._sphericalPolynomial = sp;
};
EnvironmentTextureTools2._MagicBytes = [134, 22, 135, 150, 246, 214, 150, 54];
return EnvironmentTextureTools2;
}()
);
BABYLON2.EnvironmentTextureTools = EnvironmentTextureTools;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ENVTextureLoader = (
/** @class */
function() {
function ENVTextureLoader2() {
this.supportCascades = false;
}
ENVTextureLoader2.prototype.canLoad = function(extension, textureFormatInUse, fallback, isBase64, isBuffer) {
return extension.indexOf(".env") === 0;
};
ENVTextureLoader2.prototype.transformUrl = function(rootUrl, textureFormatInUse) {
return rootUrl;
};
ENVTextureLoader2.prototype.getFallbackTextureUrl = function(rootUrl, textureFormatInUse) {
return null;
};
ENVTextureLoader2.prototype.loadCubeData = function(data2, texture, createPolynomials, onLoad, onError) {
if (Array.isArray(data2)) {
return;
}
data2 = data2;
var info = BABYLON2.EnvironmentTextureTools.GetEnvInfo(data2);
if (info) {
texture.width = info.width;
texture.height = info.width;
BABYLON2.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
BABYLON2.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data2, info).then(function() {
texture.isReady = true;
if (onLoad) {
onLoad();
}
});
} else if (onError) {
onError("Can not parse the environment file", null);
}
};
ENVTextureLoader2.prototype.loadData = function(data2, texture, callback) {
throw ".env not supported in 2d.";
};
return ENVTextureLoader2;
}()
);
BABYLON2.Engine._TextureLoaders.push(new ENVTextureLoader());
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var UtilityLayerRenderer = (
/** @class */
function() {
function UtilityLayerRenderer2(originalScene) {
var _this = this;
this.originalScene = originalScene;
this._pointerCaptures = {};
this._lastPointerEvents = {};
this.shouldRender = true;
this.onlyCheckPointerDownEvents = true;
this.processAllEvents = false;
this.onPointerOutObservable = new BABYLON2.Observable();
this.utilityLayerScene = new BABYLON2.Scene(originalScene.getEngine());
this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
this.utilityLayerScene._allowPostProcessClearColor = false;
originalScene.getEngine().scenes.pop();
this.utilityLayerScene.detachControl();
this._originalPointerObserver = originalScene.onPrePointerObservable.add(function(prePointerInfo, eventState) {
if (!_this.processAllEvents) {
if (prePointerInfo.type !== BABYLON2.PointerEventTypes.POINTERMOVE && prePointerInfo.type !== BABYLON2.PointerEventTypes.POINTERUP && prePointerInfo.type !== BABYLON2.PointerEventTypes.POINTERDOWN) {
return;
}
}
var pointerEvent = prePointerInfo.event;
if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
_this._pointerCaptures[pointerEvent.pointerId] = false;
return;
}
var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
if (!prePointerInfo.ray && utilityScenePick) {
prePointerInfo.ray = utilityScenePick.ray;
}
_this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON2.PointerEventTypes.POINTERDOWN) {
if (!prePointerInfo.skipOnPointerObservable) {
_this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON2.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
}
if (prePointerInfo.type === BABYLON2.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
_this._pointerCaptures[pointerEvent.pointerId] = false;
}
return;
}
if (_this.utilityLayerScene.autoClearDepthAndStencil) {
if (utilityScenePick && utilityScenePick.hit) {
if (!prePointerInfo.skipOnPointerObservable) {
_this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON2.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
}
prePointerInfo.skipOnPointerObservable = true;
}
} else {
var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
var pointerEvent_1 = prePointerInfo.event;
if (originalScenePick && utilityScenePick) {
if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
_this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
prePointerInfo.skipOnPointerObservable = true;
} else if (prePointerInfo.type === BABYLON2.PointerEventTypes.POINTERDOWN) {
_this._pointerCaptures[pointerEvent_1.pointerId] = true;
} else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
_this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
delete _this._lastPointerEvents[pointerEvent_1.pointerId];
}
} else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
_this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
if (!prePointerInfo.skipOnPointerObservable) {
prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
}
} else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && utilityScenePick.distance > originalScenePick.distance) {
if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
_this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
prePointerInfo.skipOnPointerObservable = true;
} else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
_this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
delete _this._lastPointerEvents[pointerEvent_1.pointerId];
}
}
if (prePointerInfo.type === BABYLON2.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
_this._pointerCaptures[pointerEvent_1.pointerId] = false;
}
}
}
});
this.utilityLayerScene.autoClear = false;
this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function() {
if (_this.shouldRender) {
_this.render();
}
});
this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function() {
_this.dispose();
});
this._updateCamera();
}
Object.defineProperty(UtilityLayerRenderer2, "DefaultUtilityLayer", {
/**
* A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
*/
get: function() {
if (UtilityLayerRenderer2._DefaultUtilityLayer == null) {
UtilityLayerRenderer2._DefaultUtilityLayer = new UtilityLayerRenderer2(BABYLON2.Engine.LastCreatedScene);
UtilityLayerRenderer2._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function() {
UtilityLayerRenderer2._DefaultUtilityLayer = null;
});
}
return UtilityLayerRenderer2._DefaultUtilityLayer;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UtilityLayerRenderer2, "DefaultKeepDepthUtilityLayer", {
/**
* A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
*/
get: function() {
if (UtilityLayerRenderer2._DefaultKeepDepthUtilityLayer == null) {
UtilityLayerRenderer2._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer2(BABYLON2.Engine.LastCreatedScene);
UtilityLayerRenderer2._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
UtilityLayerRenderer2._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function() {
UtilityLayerRenderer2._DefaultKeepDepthUtilityLayer = null;
});
}
return UtilityLayerRenderer2._DefaultKeepDepthUtilityLayer;
},
enumerable: true,
configurable: true
});
UtilityLayerRenderer2.prototype._notifyObservers = function(prePointerInfo, pickInfo, pointerEvent) {
if (!prePointerInfo.skipOnPointerObservable) {
this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON2.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
this._lastPointerEvents[pointerEvent.pointerId] = true;
}
};
UtilityLayerRenderer2.prototype.render = function() {
this._updateCamera();
if (this.utilityLayerScene.activeCamera) {
var oldScene = this.utilityLayerScene.activeCamera.getScene();
var camera2 = this.utilityLayerScene.activeCamera;
camera2._scene = this.utilityLayerScene;
if (camera2.leftCamera) {
camera2.leftCamera._scene = this.utilityLayerScene;
}
if (camera2.rightCamera) {
camera2.rightCamera._scene = this.utilityLayerScene;
}
this.utilityLayerScene.render(false);
camera2._scene = oldScene;
if (camera2.leftCamera) {
camera2.leftCamera._scene = oldScene;
}
if (camera2.rightCamera) {
camera2.rightCamera._scene = oldScene;
}
}
};
UtilityLayerRenderer2.prototype.dispose = function() {
this.onPointerOutObservable.clear();
if (this._afterRenderObserver) {
this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
}
if (this._sceneDisposeObserver) {
this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
}
if (this._originalPointerObserver) {
this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
}
this.utilityLayerScene.dispose();
};
UtilityLayerRenderer2.prototype._updateCamera = function() {
this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
};
UtilityLayerRenderer2._DefaultUtilityLayer = null;
UtilityLayerRenderer2._DefaultKeepDepthUtilityLayer = null;
return UtilityLayerRenderer2;
}()
);
BABYLON2.UtilityLayerRenderer = UtilityLayerRenderer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var PointerDragBehavior = (
/** @class */
function() {
function PointerDragBehavior2(options) {
this.maxDragAngle = 0;
this._useAlternatePickedPointAboveMaxDragAngle = false;
this.currentDraggingPointerID = -1;
this.dragging = false;
this.dragDeltaRatio = 0.2;
this.updateDragPlane = true;
this._debugMode = false;
this._moving = false;
this.onDragObservable = new BABYLON2.Observable();
this.onDragStartObservable = new BABYLON2.Observable();
this.onDragEndObservable = new BABYLON2.Observable();
this.moveAttached = true;
this.enabled = true;
this.detachCameraControls = true;
this.useObjectOrienationForDragging = true;
this._tmpVector = new BABYLON2.Vector3(0, 0, 0);
this._alternatePickedPoint = new BABYLON2.Vector3(0, 0, 0);
this._worldDragAxis = new BABYLON2.Vector3(0, 0, 0);
this._targetPosition = new BABYLON2.Vector3(0, 0, 0);
this._attachedElement = null;
this._startDragRay = new BABYLON2.Ray(new BABYLON2.Vector3(), new BABYLON2.Vector3());
this._lastPointerRay = {};
this._dragDelta = new BABYLON2.Vector3();
this._pointA = new BABYLON2.Vector3(0, 0, 0);
this._pointB = new BABYLON2.Vector3(0, 0, 0);
this._pointC = new BABYLON2.Vector3(0, 0, 0);
this._lineA = new BABYLON2.Vector3(0, 0, 0);
this._lineB = new BABYLON2.Vector3(0, 0, 0);
this._localAxis = new BABYLON2.Vector3(0, 0, 0);
this._lookAt = new BABYLON2.Vector3(0, 0, 0);
this._options = options ? options : {};
var optionCount = 0;
if (this._options.dragAxis) {
optionCount++;
}
if (this._options.dragPlaneNormal) {
optionCount++;
}
if (optionCount > 1) {
throw "Multiple drag modes specified in dragBehavior options. Only one expected";
}
}
Object.defineProperty(PointerDragBehavior2.prototype, "name", {
/**
* The name of the behavior
*/
get: function() {
return "PointerDrag";
},
enumerable: true,
configurable: true
});
PointerDragBehavior2.prototype.init = function() {
};
PointerDragBehavior2.prototype.attach = function(ownerNode) {
var _this = this;
this._scene = ownerNode.getScene();
this._attachedNode = ownerNode;
if (!PointerDragBehavior2._planeScene) {
if (this._debugMode) {
PointerDragBehavior2._planeScene = this._scene;
} else {
PointerDragBehavior2._planeScene = new BABYLON2.Scene(this._scene.getEngine());
PointerDragBehavior2._planeScene.detachControl();
this._scene.getEngine().scenes.pop();
this._scene.onDisposeObservable.addOnce(function() {
PointerDragBehavior2._planeScene.dispose();
PointerDragBehavior2._planeScene = null;
});
}
}
this._dragPlane = BABYLON2.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 1e4, PointerDragBehavior2._planeScene, false, BABYLON2.Mesh.DOUBLESIDE);
this.lastDragPosition = new BABYLON2.Vector3(0, 0, 0);
var pickPredicate = function(m) {
return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
};
this._pointerObserver = this._scene.onPointerObservable.add(function(pointerInfo, eventState) {
if (!_this.enabled) {
return;
}
if (pointerInfo.type == BABYLON2.PointerEventTypes.POINTERDOWN) {
if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
_this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
}
} else if (pointerInfo.type == BABYLON2.PointerEventTypes.POINTERUP) {
if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
_this.releaseDrag();
}
} else if (pointerInfo.type == BABYLON2.PointerEventTypes.POINTERMOVE) {
var pointerId = pointerInfo.event.pointerId;
if (_this.currentDraggingPointerID === PointerDragBehavior2._AnyMouseID && pointerId !== PointerDragBehavior2._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
_this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
delete _this._lastPointerRay[_this.currentDraggingPointerID];
}
_this.currentDraggingPointerID = pointerId;
}
if (!_this._lastPointerRay[pointerId]) {
_this._lastPointerRay[pointerId] = new BABYLON2.Ray(new BABYLON2.Vector3(), new BABYLON2.Vector3());
}
if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
_this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
_this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
_this._moveDrag(pointerInfo.pickInfo.ray);
}
}
}
});
this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function() {
if (_this._moving && _this.moveAttached) {
_this._targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
_this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
_this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
_this._attachedNode.setAbsolutePosition(_this._tmpVector);
}
});
};
PointerDragBehavior2.prototype.releaseDrag = function() {
this.dragging = false;
this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
this.currentDraggingPointerID = -1;
this._moving = false;
if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
this._scene.activeCamera.attachControl(this._attachedElement, true);
}
};
PointerDragBehavior2.prototype.startDrag = function(pointerId, fromRay, startPickedPoint) {
if (pointerId === void 0) {
pointerId = PointerDragBehavior2._AnyMouseID;
}
this._startDrag(pointerId, fromRay, startPickedPoint);
var lastRay = this._lastPointerRay[pointerId];
if (pointerId === PointerDragBehavior2._AnyMouseID) {
lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
}
if (lastRay) {
this._moveDrag(lastRay);
}
};
PointerDragBehavior2.prototype._startDrag = function(pointerId, fromRay, startPickedPoint) {
if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
return;
}
if (fromRay) {
this._startDragRay.direction.copyFrom(fromRay.direction);
this._startDragRay.origin.copyFrom(fromRay.origin);
} else {
this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
}
this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
if (pickedPoint) {
this.dragging = true;
this.currentDraggingPointerID = pointerId;
this.lastDragPosition.copyFrom(pickedPoint);
this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
this._targetPosition.copyFrom(this._attachedNode.absolutePosition);
if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
if (this._scene.activeCamera.inputs.attachedElement) {
this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
} else {
this._attachedElement = null;
}
}
}
};
PointerDragBehavior2.prototype._moveDrag = function(ray) {
this._moving = true;
var pickedPoint = this._pickWithRayOnDragPlane(ray);
if (pickedPoint) {
if (this.updateDragPlane) {
this._updateDragPlanePosition(ray, pickedPoint);
}
var dragLength = 0;
if (this._options.dragAxis) {
BABYLON2.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
dragLength = BABYLON2.Vector3.Dot(this._tmpVector, this._worldDragAxis);
this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
} else {
dragLength = this._dragDelta.length();
pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
}
this._targetPosition.addInPlace(this._dragDelta);
this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
this.lastDragPosition.copyFrom(pickedPoint);
}
};
PointerDragBehavior2.prototype._pickWithRayOnDragPlane = function(ray) {
var _this = this;
if (!ray) {
return null;
}
var angle = Math.acos(BABYLON2.Vector3.Dot(this._dragPlane.forward, ray.direction));
if (angle > Math.PI / 2) {
angle = Math.PI - angle;
}
if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
if (this._useAlternatePickedPointAboveMaxDragAngle) {
this._tmpVector.copyFrom(ray.direction);
this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
this._alternatePickedPoint.normalize();
this._alternatePickedPoint.scaleInPlace(-2 * BABYLON2.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
this._tmpVector.addInPlace(this._alternatePickedPoint);
var dot = BABYLON2.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
this._alternatePickedPoint.addInPlace(this._tmpVector);
this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
return this._alternatePickedPoint;
} else {
return null;
}
}
var pickResult = PointerDragBehavior2._planeScene.pickWithRay(ray, function(m) {
return m == _this._dragPlane;
});
if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
return pickResult.pickedPoint;
} else {
return null;
}
};
PointerDragBehavior2.prototype._updateDragPlanePosition = function(ray, dragPlanePosition) {
this._pointA.copyFrom(dragPlanePosition);
if (this._options.dragAxis) {
this.useObjectOrienationForDragging ? BABYLON2.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
this._pointA.addToRef(this._localAxis, this._pointB);
ray.origin.subtractToRef(this._pointA, this._pointC);
this._pointA.addToRef(this._pointC.normalize(), this._pointC);
this._pointB.subtractToRef(this._pointA, this._lineA);
this._pointC.subtractToRef(this._pointA, this._lineB);
BABYLON2.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
BABYLON2.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
this._lookAt.normalize();
this._dragPlane.position.copyFrom(this._pointA);
this._pointA.subtractToRef(this._lookAt, this._lookAt);
this._dragPlane.lookAt(this._lookAt);
} else if (this._options.dragPlaneNormal) {
this.useObjectOrienationForDragging ? BABYLON2.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
this._dragPlane.position.copyFrom(this._pointA);
this._pointA.subtractToRef(this._localAxis, this._lookAt);
this._dragPlane.lookAt(this._lookAt);
} else {
this._dragPlane.position.copyFrom(this._pointA);
this._dragPlane.lookAt(ray.origin);
}
this._dragPlane.computeWorldMatrix(true);
};
PointerDragBehavior2.prototype.detach = function() {
if (this._pointerObserver) {
this._scene.onPointerObservable.remove(this._pointerObserver);
}
if (this._beforeRenderObserver) {
this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
}
};
PointerDragBehavior2._AnyMouseID = -2;
return PointerDragBehavior2;
}()
);
BABYLON2.PointerDragBehavior = PointerDragBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MultiPointerScaleBehavior = (
/** @class */
function() {
function MultiPointerScaleBehavior2() {
this._startDistance = 0;
this._initialScale = new BABYLON2.Vector3(0, 0, 0);
this._targetScale = new BABYLON2.Vector3(0, 0, 0);
this._sceneRenderObserver = null;
this._dragBehaviorA = new BABYLON2.PointerDragBehavior({});
this._dragBehaviorA.moveAttached = false;
this._dragBehaviorB = new BABYLON2.PointerDragBehavior({});
this._dragBehaviorB.moveAttached = false;
}
Object.defineProperty(MultiPointerScaleBehavior2.prototype, "name", {
/**
* The name of the behavior
*/
get: function() {
return "MultiPointerScale";
},
enumerable: true,
configurable: true
});
MultiPointerScaleBehavior2.prototype.init = function() {
};
MultiPointerScaleBehavior2.prototype._getCurrentDistance = function() {
return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
};
MultiPointerScaleBehavior2.prototype.attach = function(ownerNode) {
var _this = this;
this._ownerNode = ownerNode;
this._dragBehaviorA.onDragStartObservable.add(function(e2) {
if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
_this._dragBehaviorA.releaseDrag();
} else {
_this._initialScale.copyFrom(ownerNode.scaling);
_this._startDistance = _this._getCurrentDistance();
}
}
});
this._dragBehaviorB.onDragStartObservable.add(function(e2) {
if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
_this._dragBehaviorB.releaseDrag();
} else {
_this._initialScale.copyFrom(ownerNode.scaling);
_this._startDistance = _this._getCurrentDistance();
}
}
});
[this._dragBehaviorA, this._dragBehaviorB].forEach(function(behavior) {
behavior.onDragObservable.add(function() {
if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
var ratio = _this._getCurrentDistance() / _this._startDistance;
_this._initialScale.scaleToRef(ratio, _this._targetScale);
}
});
});
ownerNode.addBehavior(this._dragBehaviorA);
ownerNode.addBehavior(this._dragBehaviorB);
this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function() {
if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
if (change.length() > 0.01) {
ownerNode.scaling.addInPlace(change);
}
}
});
};
MultiPointerScaleBehavior2.prototype.detach = function() {
var _this = this;
this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
[this._dragBehaviorA, this._dragBehaviorB].forEach(function(behavior) {
behavior.onDragStartObservable.clear();
behavior.onDragObservable.clear();
_this._ownerNode.removeBehavior(behavior);
});
};
return MultiPointerScaleBehavior2;
}()
);
BABYLON2.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SixDofDragBehavior = (
/** @class */
function() {
function SixDofDragBehavior2() {
this._sceneRenderObserver = null;
this._targetPosition = new BABYLON2.Vector3(0, 0, 0);
this._moving = false;
this._startingOrientation = new BABYLON2.Quaternion();
this.zDragFactor = 3;
this.dragging = false;
this.dragDeltaRatio = 0.2;
this.currentDraggingPointerID = -1;
this.detachCameraControls = true;
this.onDragStartObservable = new BABYLON2.Observable();
this.onDragEndObservable = new BABYLON2.Observable();
}
Object.defineProperty(SixDofDragBehavior2.prototype, "name", {
/**
* The name of the behavior
*/
get: function() {
return "SixDofDrag";
},
enumerable: true,
configurable: true
});
SixDofDragBehavior2.prototype.init = function() {
};
SixDofDragBehavior2.prototype.attach = function(ownerNode) {
var _this = this;
this._ownerNode = ownerNode;
this._scene = this._ownerNode.getScene();
if (!SixDofDragBehavior2._virtualScene) {
SixDofDragBehavior2._virtualScene = new BABYLON2.Scene(this._scene.getEngine());
SixDofDragBehavior2._virtualScene.detachControl();
this._scene.getEngine().scenes.pop();
}
var pickedMesh = null;
var lastSixDofOriginPosition = new BABYLON2.Vector3(0, 0, 0);
this._virtualOriginMesh = new BABYLON2.AbstractMesh("", SixDofDragBehavior2._virtualScene);
this._virtualOriginMesh.rotationQuaternion = new BABYLON2.Quaternion();
this._virtualDragMesh = new BABYLON2.AbstractMesh("", SixDofDragBehavior2._virtualScene);
this._virtualDragMesh.rotationQuaternion = new BABYLON2.Quaternion();
var pickPredicate = function(m) {
return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
};
var attachedElement = null;
this._pointerObserver = this._scene.onPointerObservable.add(function(pointerInfo, eventState) {
if (pointerInfo.type == BABYLON2.PointerEventTypes.POINTERDOWN) {
if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON2.Camera.RIG_MODE_NONE) {
pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
}
pickedMesh = _this._ownerNode;
lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
_this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
_this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
_this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
pickedMesh.computeWorldMatrix();
_this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
if (!pickedMesh.rotationQuaternion) {
pickedMesh.rotationQuaternion = BABYLON2.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
}
var oldParent = pickedMesh.parent;
pickedMesh.setParent(null);
_this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
pickedMesh.setParent(oldParent);
_this._virtualOriginMesh.addChild(_this._virtualDragMesh);
_this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
_this.dragging = true;
_this.currentDraggingPointerID = pointerInfo.event.pointerId;
if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
if (_this._scene.activeCamera.inputs.attachedElement) {
attachedElement = _this._scene.activeCamera.inputs.attachedElement;
_this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
} else {
attachedElement = null;
}
}
_this.onDragStartObservable.notifyObservers({});
}
} else if (pointerInfo.type == BABYLON2.PointerEventTypes.POINTERUP) {
if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
_this.dragging = false;
_this._moving = false;
_this.currentDraggingPointerID = -1;
pickedMesh = null;
_this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
_this._scene.activeCamera.attachControl(attachedElement, true);
}
_this.onDragEndObservable.notifyObservers({});
}
} else if (pointerInfo.type == BABYLON2.PointerEventTypes.POINTERMOVE) {
if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
var zDragFactor = _this.zDragFactor;
if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON2.Camera.RIG_MODE_NONE) {
pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
zDragFactor = 0;
}
var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
var localOriginDragDifference = -BABYLON2.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
_this._virtualOriginMesh.addChild(_this._virtualDragMesh);
_this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
if (_this._virtualDragMesh.position.z < 0) {
_this._virtualDragMesh.position.z = 0;
}
_this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
_this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
_this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
_this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
if (pickedMesh.parent) {
BABYLON2.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON2.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
}
if (!_this._moving) {
_this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
}
_this._moving = true;
}
}
});
var tmpQuaternion = new BABYLON2.Quaternion();
this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function() {
if (_this.dragging && _this._moving && pickedMesh) {
pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
tmpQuaternion.copyFrom(_this._startingOrientation);
tmpQuaternion.x = -tmpQuaternion.x;
tmpQuaternion.y = -tmpQuaternion.y;
tmpQuaternion.z = -tmpQuaternion.z;
_this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
BABYLON2.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
var oldParent = pickedMesh.parent;
pickedMesh.setParent(null);
BABYLON2.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
pickedMesh.setParent(oldParent);
}
});
};
SixDofDragBehavior2.prototype.detach = function() {
if (this._scene) {
this._scene.onPointerObservable.remove(this._pointerObserver);
}
if (this._ownerNode) {
this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
}
if (this._virtualOriginMesh) {
this._virtualOriginMesh.dispose();
}
if (this._virtualDragMesh) {
this._virtualDragMesh.dispose();
}
this.onDragEndObservable.clear();
this.onDragStartObservable.clear();
};
return SixDofDragBehavior2;
}()
);
BABYLON2.SixDofDragBehavior = SixDofDragBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FaceDirectionInfo = (
/** @class */
function() {
function FaceDirectionInfo2(direction, rotatedDirection, diff, ignore) {
if (rotatedDirection === void 0) {
rotatedDirection = new BABYLON2.Vector3();
}
if (diff === void 0) {
diff = 0;
}
if (ignore === void 0) {
ignore = false;
}
this.direction = direction;
this.rotatedDirection = rotatedDirection;
this.diff = diff;
this.ignore = ignore;
}
return FaceDirectionInfo2;
}()
);
var AttachToBoxBehavior = (
/** @class */
function() {
function AttachToBoxBehavior2(ui) {
this.ui = ui;
this.name = "AttachToBoxBehavior";
this.distanceAwayFromFace = 0.15;
this.distanceAwayFromBottomOfFace = 0.15;
this._faceVectors = [new FaceDirectionInfo(BABYLON2.Vector3.Up()), new FaceDirectionInfo(BABYLON2.Vector3.Down()), new FaceDirectionInfo(BABYLON2.Vector3.Left()), new FaceDirectionInfo(BABYLON2.Vector3.Right()), new FaceDirectionInfo(BABYLON2.Vector3.Forward()), new FaceDirectionInfo(BABYLON2.Vector3.Forward().scaleInPlace(-1))];
this._tmpMatrix = new BABYLON2.Matrix();
this._tmpVector = new BABYLON2.Vector3();
this._zeroVector = BABYLON2.Vector3.Zero();
this._lookAtTmpMatrix = new BABYLON2.Matrix();
}
AttachToBoxBehavior2.prototype.init = function() {
};
AttachToBoxBehavior2.prototype._closestFace = function(targetDirection) {
var _this = this;
this._faceVectors.forEach(function(v) {
if (!_this._target.rotationQuaternion) {
_this._target.rotationQuaternion = BABYLON2.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
}
_this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
BABYLON2.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
v.diff = BABYLON2.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON2.Vector3.Cross(v.rotatedDirection, targetDirection));
});
return this._faceVectors.reduce(function(min, p) {
if (min.ignore) {
return p;
} else if (p.ignore) {
return min;
} else {
return min.diff < p.diff ? min : p;
}
}, this._faceVectors[0]);
};
AttachToBoxBehavior2.prototype._lookAtToRef = function(pos, up, ref) {
if (up === void 0) {
up = new BABYLON2.Vector3(0, 1, 0);
}
BABYLON2.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
this._lookAtTmpMatrix.invert();
BABYLON2.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
};
AttachToBoxBehavior2.prototype.attach = function(target) {
var _this = this;
this._target = target;
this._scene = this._target.getScene();
this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function() {
if (!_this._scene.activeCamera) {
return;
}
var cameraPos = _this._scene.activeCamera.position;
if (_this._scene.activeCamera.devicePosition) {
cameraPos = _this._scene.activeCamera.devicePosition;
}
var facing = _this._closestFace(cameraPos.subtract(target.position));
if (_this._scene.activeCamera.leftCamera) {
_this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
} else {
_this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
}
BABYLON2.Vector3.TransformCoordinatesToRef(BABYLON2.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
_this._faceVectors.forEach(function(v) {
if (facing.direction.x && v.direction.x) {
v.ignore = true;
}
if (facing.direction.y && v.direction.y) {
v.ignore = true;
}
if (facing.direction.z && v.direction.z) {
v.ignore = true;
}
});
var facingUp = _this._closestFace(_this._tmpVector);
_this._faceVectors.forEach(function(v) {
v.ignore = false;
});
_this.ui.position.copyFrom(target.position);
if (facing.direction.x) {
facing.rotatedDirection.scaleToRef(target.scaling.x / 2 + _this.distanceAwayFromFace, _this._tmpVector);
_this.ui.position.addInPlace(_this._tmpVector);
}
if (facing.direction.y) {
facing.rotatedDirection.scaleToRef(target.scaling.y / 2 + _this.distanceAwayFromFace, _this._tmpVector);
_this.ui.position.addInPlace(_this._tmpVector);
}
if (facing.direction.z) {
facing.rotatedDirection.scaleToRef(target.scaling.z / 2 + _this.distanceAwayFromFace, _this._tmpVector);
_this.ui.position.addInPlace(_this._tmpVector);
}
if (!_this.ui.rotationQuaternion) {
_this.ui.rotationQuaternion = BABYLON2.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
}
facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
_this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
if (facingUp.direction.x) {
_this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
}
if (facingUp.direction.y) {
_this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
}
if (facingUp.direction.z) {
_this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
}
_this.ui.position.addInPlace(_this._tmpVector);
});
};
AttachToBoxBehavior2.prototype.detach = function() {
this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
};
return AttachToBoxBehavior2;
}()
);
BABYLON2.AttachToBoxBehavior = AttachToBoxBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FadeInOutBehavior = (
/** @class */
function() {
function FadeInOutBehavior2() {
var _this = this;
this.delay = 0;
this.fadeInTime = 300;
this._millisecondsPerFrame = 1e3 / 60;
this._hovered = false;
this._hoverValue = 0;
this._ownerNode = null;
this._update = function() {
if (_this._ownerNode) {
_this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
_this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
if (_this._ownerNode.visibility > 1) {
_this._setAllVisibility(_this._ownerNode, 1);
_this._hoverValue = _this.fadeInTime + _this.delay;
return;
} else if (_this._ownerNode.visibility < 0) {
_this._setAllVisibility(_this._ownerNode, 0);
if (_this._hoverValue < 0) {
_this._hoverValue = 0;
return;
}
}
setTimeout(_this._update, _this._millisecondsPerFrame);
}
};
}
Object.defineProperty(FadeInOutBehavior2.prototype, "name", {
/**
* The name of the behavior
*/
get: function() {
return "FadeInOut";
},
enumerable: true,
configurable: true
});
FadeInOutBehavior2.prototype.init = function() {
};
FadeInOutBehavior2.prototype.attach = function(ownerNode) {
this._ownerNode = ownerNode;
this._setAllVisibility(this._ownerNode, 0);
};
FadeInOutBehavior2.prototype.detach = function() {
this._ownerNode = null;
};
FadeInOutBehavior2.prototype.fadeIn = function(value) {
this._hovered = value;
this._update();
};
FadeInOutBehavior2.prototype._setAllVisibility = function(mesh2, value) {
var _this = this;
mesh2.visibility = value;
mesh2.getChildMeshes().forEach(function(c) {
_this._setAllVisibility(c, value);
});
};
return FadeInOutBehavior2;
}()
);
BABYLON2.FadeInOutBehavior = FadeInOutBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MorphTarget = (
/** @class */
function() {
function MorphTarget2(name, influence, scene) {
if (influence === void 0) {
influence = 0;
}
if (scene === void 0) {
scene = null;
}
this.name = name;
this.animations = new Array();
this._positions = null;
this._normals = null;
this._tangents = null;
this.onInfluenceChanged = new BABYLON2.Observable();
this._onDataLayoutChanged = new BABYLON2.Observable();
this._animationPropertiesOverride = null;
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
this.influence = influence;
}
Object.defineProperty(MorphTarget2.prototype, "influence", {
/**
* Gets or sets the influence of this target (ie. its weight in the overall morphing)
*/
get: function() {
return this._influence;
},
set: function(influence) {
if (this._influence === influence) {
return;
}
var previous = this._influence;
this._influence = influence;
if (this.onInfluenceChanged.hasObservers) {
this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTarget2.prototype, "animationPropertiesOverride", {
/**
* Gets or sets the animation properties override
*/
get: function() {
if (!this._animationPropertiesOverride && this._scene) {
return this._scene.animationPropertiesOverride;
}
return this._animationPropertiesOverride;
},
set: function(value) {
this._animationPropertiesOverride = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTarget2.prototype, "hasPositions", {
/**
* Gets a boolean defining if the target contains position data
*/
get: function() {
return !!this._positions;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTarget2.prototype, "hasNormals", {
/**
* Gets a boolean defining if the target contains normal data
*/
get: function() {
return !!this._normals;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTarget2.prototype, "hasTangents", {
/**
* Gets a boolean defining if the target contains tangent data
*/
get: function() {
return !!this._tangents;
},
enumerable: true,
configurable: true
});
MorphTarget2.prototype.setPositions = function(data2) {
var hadPositions = this.hasPositions;
this._positions = data2;
if (hadPositions !== this.hasPositions) {
this._onDataLayoutChanged.notifyObservers(void 0);
}
};
MorphTarget2.prototype.getPositions = function() {
return this._positions;
};
MorphTarget2.prototype.setNormals = function(data2) {
var hadNormals = this.hasNormals;
this._normals = data2;
if (hadNormals !== this.hasNormals) {
this._onDataLayoutChanged.notifyObservers(void 0);
}
};
MorphTarget2.prototype.getNormals = function() {
return this._normals;
};
MorphTarget2.prototype.setTangents = function(data2) {
var hadTangents = this.hasTangents;
this._tangents = data2;
if (hadTangents !== this.hasTangents) {
this._onDataLayoutChanged.notifyObservers(void 0);
}
};
MorphTarget2.prototype.getTangents = function() {
return this._tangents;
};
MorphTarget2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.influence = this.influence;
serializationObject.positions = Array.prototype.slice.call(this.getPositions());
if (this.hasNormals) {
serializationObject.normals = Array.prototype.slice.call(this.getNormals());
}
if (this.hasTangents) {
serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
}
BABYLON2.Animation.AppendSerializedAnimations(this, serializationObject);
return serializationObject;
};
MorphTarget2.Parse = function(serializationObject) {
var result = new MorphTarget2(serializationObject.name, serializationObject.influence);
result.setPositions(serializationObject.positions);
if (serializationObject.normals) {
result.setNormals(serializationObject.normals);
}
if (serializationObject.tangents) {
result.setTangents(serializationObject.tangents);
}
if (serializationObject.animations) {
for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
var parsedAnimation = serializationObject.animations[animationIndex];
result.animations.push(BABYLON2.Animation.Parse(parsedAnimation));
}
}
return result;
};
MorphTarget2.FromMesh = function(mesh2, name, influence) {
if (!name) {
name = mesh2.name;
}
var result = new MorphTarget2(name, influence, mesh2.getScene());
result.setPositions(mesh2.getVerticesData(BABYLON2.VertexBuffer.PositionKind));
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
result.setNormals(mesh2.getVerticesData(BABYLON2.VertexBuffer.NormalKind));
}
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.TangentKind)) {
result.setTangents(mesh2.getVerticesData(BABYLON2.VertexBuffer.TangentKind));
}
return result;
};
return MorphTarget2;
}()
);
BABYLON2.MorphTarget = MorphTarget;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MorphTargetManager = (
/** @class */
function() {
function MorphTargetManager2(scene) {
if (scene === void 0) {
scene = null;
}
this._targets = new Array();
this._targetInfluenceChangedObservers = new Array();
this._targetDataLayoutChangedObservers = new Array();
this._activeTargets = new BABYLON2.SmartArray(16);
this._supportsNormals = false;
this._supportsTangents = false;
this._vertexCount = 0;
this._uniqueId = 0;
this._tempInfluences = new Array();
if (!scene) {
scene = BABYLON2.Engine.LastCreatedScene;
}
this._scene = scene;
if (this._scene) {
this._scene.morphTargetManagers.push(this);
this._uniqueId = this._scene.getUniqueId();
}
}
Object.defineProperty(MorphTargetManager2.prototype, "uniqueId", {
/**
* Gets the unique ID of this manager
*/
get: function() {
return this._uniqueId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTargetManager2.prototype, "vertexCount", {
/**
* Gets the number of vertices handled by this manager
*/
get: function() {
return this._vertexCount;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTargetManager2.prototype, "supportsNormals", {
/**
* Gets a boolean indicating if this manager supports morphing of normals
*/
get: function() {
return this._supportsNormals;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTargetManager2.prototype, "supportsTangents", {
/**
* Gets a boolean indicating if this manager supports morphing of tangents
*/
get: function() {
return this._supportsTangents;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTargetManager2.prototype, "numTargets", {
/**
* Gets the number of targets stored in this manager
*/
get: function() {
return this._targets.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTargetManager2.prototype, "numInfluencers", {
/**
* Gets the number of influencers (ie. the number of targets with influences > 0)
*/
get: function() {
return this._activeTargets.length;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MorphTargetManager2.prototype, "influences", {
/**
* Gets the list of influences (one per target)
*/
get: function() {
return this._influences;
},
enumerable: true,
configurable: true
});
MorphTargetManager2.prototype.getActiveTarget = function(index) {
return this._activeTargets.data[index];
};
MorphTargetManager2.prototype.getTarget = function(index) {
return this._targets[index];
};
MorphTargetManager2.prototype.addTarget = function(target) {
var _this = this;
this._targets.push(target);
this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function(needUpdate) {
_this._syncActiveTargets(needUpdate);
}));
this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function() {
_this._syncActiveTargets(true);
}));
this._syncActiveTargets(true);
};
MorphTargetManager2.prototype.removeTarget = function(target) {
var index = this._targets.indexOf(target);
if (index >= 0) {
this._targets.splice(index, 1);
target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
this._syncActiveTargets(true);
}
};
MorphTargetManager2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.id = this.uniqueId;
serializationObject.targets = [];
for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
var target = _a[_i];
serializationObject.targets.push(target.serialize());
}
return serializationObject;
};
MorphTargetManager2.prototype._syncActiveTargets = function(needUpdate) {
var influenceCount = 0;
this._activeTargets.reset();
this._supportsNormals = true;
this._supportsTangents = true;
this._vertexCount = 0;
for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
var target = _a[_i];
if (target.influence === 0) {
continue;
}
this._activeTargets.push(target);
this._tempInfluences[influenceCount++] = target.influence;
this._supportsNormals = this._supportsNormals && target.hasNormals;
this._supportsTangents = this._supportsTangents && target.hasTangents;
var positions = target.getPositions();
if (positions) {
var vertexCount = positions.length / 3;
if (this._vertexCount === 0) {
this._vertexCount = vertexCount;
} else if (this._vertexCount !== vertexCount) {
BABYLON2.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
return;
}
}
}
if (!this._influences || this._influences.length !== influenceCount) {
this._influences = new Float32Array(influenceCount);
}
for (var index = 0; index < influenceCount; index++) {
this._influences[index] = this._tempInfluences[index];
}
if (needUpdate) {
this.synchronize();
}
};
MorphTargetManager2.prototype.synchronize = function() {
if (!this._scene) {
return;
}
for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
var mesh2 = _a[_i];
if (mesh2.morphTargetManager === this) {
mesh2._syncGeometryWithMorphTargetManager();
}
}
};
MorphTargetManager2.Parse = function(serializationObject, scene) {
var result = new MorphTargetManager2(scene);
result._uniqueId = serializationObject.id;
for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
var targetData = _a[_i];
result.addTarget(BABYLON2.MorphTarget.Parse(targetData));
}
return result;
};
return MorphTargetManager2;
}()
);
BABYLON2.MorphTargetManager = MorphTargetManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Octree = (
/** @class */
function() {
function Octree2(creationFunc, maxBlockCapacity, maxDepth) {
if (maxDepth === void 0) {
maxDepth = 2;
}
this.maxDepth = maxDepth;
this.dynamicContent = new Array();
this._maxBlockCapacity = maxBlockCapacity || 64;
this._selectionContent = new BABYLON2.SmartArrayNoDuplicate(1024);
this._creationFunc = creationFunc;
}
Octree2.prototype.update = function(worldMin, worldMax, entries) {
Octree2._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
};
Octree2.prototype.addMesh = function(entry) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.addEntry(entry);
}
};
Octree2.prototype.select = function(frustumPlanes, allowDuplicate) {
this._selectionContent.reset();
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.select(frustumPlanes, this._selectionContent, allowDuplicate);
}
if (allowDuplicate) {
this._selectionContent.concat(this.dynamicContent);
} else {
this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
}
return this._selectionContent;
};
Octree2.prototype.intersects = function(sphereCenter, sphereRadius, allowDuplicate) {
this._selectionContent.reset();
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
}
if (allowDuplicate) {
this._selectionContent.concat(this.dynamicContent);
} else {
this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
}
return this._selectionContent;
};
Octree2.prototype.intersectsRay = function(ray) {
this._selectionContent.reset();
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersectsRay(ray, this._selectionContent);
}
this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
return this._selectionContent;
};
Octree2._CreateBlocks = function(worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
target.blocks = new Array();
var blockSize = new BABYLON2.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
for (var x = 0; x < 2; x++) {
for (var y = 0; y < 2; y++) {
for (var z = 0; z < 2; z++) {
var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
var block = new BABYLON2.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
block.addEntries(entries);
target.blocks.push(block);
}
}
}
};
Octree2.CreationFuncForMeshes = function(entry, block) {
var boundingInfo = entry.getBoundingInfo();
if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
block.entries.push(entry);
}
};
Octree2.CreationFuncForSubMeshes = function(entry, block) {
var boundingInfo = entry.getBoundingInfo();
if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
block.entries.push(entry);
}
};
return Octree2;
}()
);
BABYLON2.Octree = Octree;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var OctreeBlock = (
/** @class */
function() {
function OctreeBlock2(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
this.entries = new Array();
this._boundingVectors = new Array();
this._capacity = capacity;
this._depth = depth;
this._maxDepth = maxDepth;
this._creationFunc = creationFunc;
this._minPoint = minPoint;
this._maxPoint = maxPoint;
this._boundingVectors.push(minPoint.clone());
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors.push(minPoint.clone());
this._boundingVectors[2].x = maxPoint.x;
this._boundingVectors.push(minPoint.clone());
this._boundingVectors[3].y = maxPoint.y;
this._boundingVectors.push(minPoint.clone());
this._boundingVectors[4].z = maxPoint.z;
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors[5].z = minPoint.z;
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors[6].x = minPoint.x;
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors[7].y = minPoint.y;
}
Object.defineProperty(OctreeBlock2.prototype, "capacity", {
// Property
/**
* Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
*/
get: function() {
return this._capacity;
},
enumerable: true,
configurable: true
});
Object.defineProperty(OctreeBlock2.prototype, "minPoint", {
/**
* Gets the minimum vector (in world space) of the block's bounding box
*/
get: function() {
return this._minPoint;
},
enumerable: true,
configurable: true
});
Object.defineProperty(OctreeBlock2.prototype, "maxPoint", {
/**
* Gets the maximum vector (in world space) of the block's bounding box
*/
get: function() {
return this._maxPoint;
},
enumerable: true,
configurable: true
});
OctreeBlock2.prototype.addEntry = function(entry) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.addEntry(entry);
}
return;
}
this._creationFunc(entry, this);
if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
this.createInnerBlocks();
}
};
OctreeBlock2.prototype.addEntries = function(entries) {
for (var index = 0; index < entries.length; index++) {
var mesh2 = entries[index];
this.addEntry(mesh2);
}
};
OctreeBlock2.prototype.select = function(frustumPlanes, selection, allowDuplicate) {
if (BABYLON2.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.select(frustumPlanes, selection, allowDuplicate);
}
return;
}
if (allowDuplicate) {
selection.concat(this.entries);
} else {
selection.concatWithNoDuplicate(this.entries);
}
}
};
OctreeBlock2.prototype.intersects = function(sphereCenter, sphereRadius, selection, allowDuplicate) {
if (BABYLON2.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
}
return;
}
if (allowDuplicate) {
selection.concat(this.entries);
} else {
selection.concatWithNoDuplicate(this.entries);
}
}
};
OctreeBlock2.prototype.intersectsRay = function(ray, selection) {
if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersectsRay(ray, selection);
}
return;
}
selection.concatWithNoDuplicate(this.entries);
}
};
OctreeBlock2.prototype.createInnerBlocks = function() {
BABYLON2.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
};
return OctreeBlock2;
}()
);
BABYLON2.OctreeBlock = OctreeBlock;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Scene.prototype.createOrUpdateSelectionOctree = function(maxCapacity, maxDepth) {
if (maxCapacity === void 0) {
maxCapacity = 64;
}
if (maxDepth === void 0) {
maxDepth = 2;
}
var component = this._getComponent(BABYLON2.SceneComponentConstants.NAME_OCTREE);
if (!component) {
component = new OctreeSceneComponent(this);
this._addComponent(component);
}
if (!this._selectionOctree) {
this._selectionOctree = new BABYLON2.Octree(BABYLON2.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
}
var worldExtends = this.getWorldExtends();
this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
return this._selectionOctree;
};
Object.defineProperty(BABYLON2.Scene.prototype, "selectionOctree", {
get: function() {
return this._selectionOctree;
},
enumerable: true,
configurable: true
});
BABYLON2.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function(maxCapacity, maxDepth) {
if (maxCapacity === void 0) {
maxCapacity = 64;
}
if (maxDepth === void 0) {
maxDepth = 2;
}
var scene = this.getScene();
var component = scene._getComponent(BABYLON2.SceneComponentConstants.NAME_OCTREE);
if (!component) {
component = new OctreeSceneComponent(scene);
scene._addComponent(component);
}
if (!this._submeshesOctree) {
this._submeshesOctree = new BABYLON2.Octree(BABYLON2.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
}
this.computeWorldMatrix(true);
var boundingInfo = this.getBoundingInfo();
var bbox = boundingInfo.boundingBox;
this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
return this._submeshesOctree;
};
var OctreeSceneComponent = (
/** @class */
function() {
function OctreeSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_OCTREE;
this.checksIsEnabled = true;
this._tempRay = new BABYLON2.Ray(BABYLON2.Vector3.Zero(), new BABYLON2.Vector3(1, 1, 1));
this.scene = scene;
this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
}
OctreeSceneComponent2.prototype.register = function() {
var _this = this;
this.scene.onMeshRemovedObservable.add(function(mesh2) {
var sceneOctree = _this.scene.selectionOctree;
if (sceneOctree !== void 0 && sceneOctree !== null) {
var index = sceneOctree.dynamicContent.indexOf(mesh2);
if (index !== -1) {
sceneOctree.dynamicContent.splice(index, 1);
}
}
});
this.scene.onMeshImportedObservable.add(function(mesh2) {
var sceneOctree = _this.scene.selectionOctree;
if (sceneOctree !== void 0 && sceneOctree !== null) {
sceneOctree.addMesh(mesh2);
}
});
};
OctreeSceneComponent2.prototype.getActiveMeshCandidates = function() {
if (this.scene._selectionOctree) {
var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
return selection;
}
return this.scene._getDefaultMeshCandidates();
};
OctreeSceneComponent2.prototype.getActiveSubMeshCandidates = function(mesh2) {
if (mesh2._submeshesOctree && mesh2.useOctreeForRenderingSelection) {
var intersections = mesh2._submeshesOctree.select(this.scene.frustumPlanes);
return intersections;
}
return this.scene._getDefaultSubMeshCandidates(mesh2);
};
OctreeSceneComponent2.prototype.getIntersectingSubMeshCandidates = function(mesh2, localRay) {
if (mesh2._submeshesOctree && mesh2.useOctreeForPicking) {
BABYLON2.Ray.TransformToRef(localRay, mesh2.getWorldMatrix(), this._tempRay);
var intersections = mesh2._submeshesOctree.intersectsRay(this._tempRay);
return intersections;
}
return this.scene._getDefaultSubMeshCandidates(mesh2);
};
OctreeSceneComponent2.prototype.getCollidingSubMeshCandidates = function(mesh2, collider) {
if (mesh2._submeshesOctree && mesh2.useOctreeForCollisions) {
var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
var intersections = mesh2._submeshesOctree.intersects(collider._basePointWorld, radius);
return intersections;
}
return this.scene._getDefaultSubMeshCandidates(mesh2);
};
OctreeSceneComponent2.prototype.rebuild = function() {
};
OctreeSceneComponent2.prototype.dispose = function() {
};
return OctreeSceneComponent2;
}()
);
BABYLON2.OctreeSceneComponent = OctreeSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SimplificationSettings = (
/** @class */
function() {
function SimplificationSettings2(quality, distance, optimizeMesh) {
this.quality = quality;
this.distance = distance;
this.optimizeMesh = optimizeMesh;
}
return SimplificationSettings2;
}()
);
BABYLON2.SimplificationSettings = SimplificationSettings;
var SimplificationQueue = (
/** @class */
function() {
function SimplificationQueue2() {
this.running = false;
this._simplificationArray = [];
}
SimplificationQueue2.prototype.addTask = function(task) {
this._simplificationArray.push(task);
};
SimplificationQueue2.prototype.executeNext = function() {
var task = this._simplificationArray.pop();
if (task) {
this.running = true;
this.runSimplification(task);
} else {
this.running = false;
}
};
SimplificationQueue2.prototype.runSimplification = function(task) {
var _this = this;
if (task.parallelProcessing) {
task.settings.forEach(function(setting) {
var simplifier2 = _this.getSimplifier(task);
simplifier2.simplify(setting, function(newMesh) {
task.mesh.addLODLevel(setting.distance, newMesh);
newMesh.isVisible = true;
if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
task.successCallback();
}
_this.executeNext();
});
});
} else {
var simplifier = this.getSimplifier(task);
var runDecimation = function(setting, callback) {
simplifier.simplify(setting, function(newMesh) {
task.mesh.addLODLevel(setting.distance, newMesh);
newMesh.isVisible = true;
callback();
});
};
BABYLON2.AsyncLoop.Run(task.settings.length, function(loop) {
runDecimation(task.settings[loop.index], function() {
loop.executeNext();
});
}, function() {
if (task.successCallback) {
task.successCallback();
}
_this.executeNext();
});
}
};
SimplificationQueue2.prototype.getSimplifier = function(task) {
switch (task.simplificationType) {
case SimplificationType.QUADRATIC:
default:
return new QuadraticErrorSimplification(task.mesh);
}
};
return SimplificationQueue2;
}()
);
BABYLON2.SimplificationQueue = SimplificationQueue;
var SimplificationType;
(function(SimplificationType2) {
SimplificationType2[SimplificationType2["QUADRATIC"] = 0] = "QUADRATIC";
})(SimplificationType = BABYLON2.SimplificationType || (BABYLON2.SimplificationType = {}));
var DecimationTriangle = (
/** @class */
function() {
function DecimationTriangle2(vertices) {
this.vertices = vertices;
this.error = new Array(4);
this.deleted = false;
this.isDirty = false;
this.deletePending = false;
this.borderFactor = 0;
}
return DecimationTriangle2;
}()
);
var DecimationVertex = (
/** @class */
function() {
function DecimationVertex2(position, id) {
this.position = position;
this.id = id;
this.isBorder = true;
this.q = new QuadraticMatrix();
this.triangleCount = 0;
this.triangleStart = 0;
this.originalOffsets = [];
}
DecimationVertex2.prototype.updatePosition = function(newPosition) {
this.position.copyFrom(newPosition);
};
return DecimationVertex2;
}()
);
var QuadraticMatrix = (
/** @class */
function() {
function QuadraticMatrix2(data2) {
this.data = new Array(10);
for (var i2 = 0; i2 < 10; ++i2) {
if (data2 && data2[i2]) {
this.data[i2] = data2[i2];
} else {
this.data[i2] = 0;
}
}
}
QuadraticMatrix2.prototype.det = function(a11, a12, a13, a21, a22, a23, a31, a32, a33) {
var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
return det;
};
QuadraticMatrix2.prototype.addInPlace = function(matrix) {
for (var i2 = 0; i2 < 10; ++i2) {
this.data[i2] += matrix.data[i2];
}
};
QuadraticMatrix2.prototype.addArrayInPlace = function(data2) {
for (var i2 = 0; i2 < 10; ++i2) {
this.data[i2] += data2[i2];
}
};
QuadraticMatrix2.prototype.add = function(matrix) {
var m = new QuadraticMatrix2();
for (var i2 = 0; i2 < 10; ++i2) {
m.data[i2] = this.data[i2] + matrix.data[i2];
}
return m;
};
QuadraticMatrix2.FromData = function(a, b2, c, d) {
return new QuadraticMatrix2(QuadraticMatrix2.DataFromNumbers(a, b2, c, d));
};
QuadraticMatrix2.DataFromNumbers = function(a, b2, c, d) {
return [a * a, a * b2, a * c, a * d, b2 * b2, b2 * c, b2 * d, c * c, c * d, d * d];
};
return QuadraticMatrix2;
}()
);
var Reference = (
/** @class */
function() {
function Reference2(vertexId, triangleId) {
this.vertexId = vertexId;
this.triangleId = triangleId;
}
return Reference2;
}()
);
var QuadraticErrorSimplification = (
/** @class */
function() {
function QuadraticErrorSimplification2(_mesh) {
this._mesh = _mesh;
this.syncIterations = 5e3;
this.aggressiveness = 7;
this.decimationIterations = 100;
this.boundingBoxEpsilon = BABYLON2.Epsilon;
}
QuadraticErrorSimplification2.prototype.simplify = function(settings2, successCallback2) {
var _this = this;
this.initDecimatedMesh();
BABYLON2.AsyncLoop.Run(this._mesh.subMeshes.length, function(loop) {
_this.initWithMesh(loop.index, function() {
_this.runDecimation(settings2, loop.index, function() {
loop.executeNext();
});
}, settings2.optimizeMesh);
}, function() {
setTimeout(function() {
successCallback2(_this._reconstructedMesh);
}, 0);
});
};
QuadraticErrorSimplification2.prototype.runDecimation = function(settings2, submeshIndex, successCallback2) {
var _this = this;
var targetCount = ~~(this.triangles.length * settings2.quality);
var deletedTriangles = 0;
var triangleCount = this.triangles.length;
var iterationFunction = function(iteration, callback) {
setTimeout(function() {
if (iteration % 5 === 0) {
_this.updateMesh(iteration === 0);
}
for (var i2 = 0; i2 < _this.triangles.length; ++i2) {
_this.triangles[i2].isDirty = false;
}
var threshold = 1e-9 * Math.pow(iteration + 3, _this.aggressiveness);
var trianglesIterator = function(i3) {
var tIdx = ~~((_this.triangles.length / 2 + i3) % _this.triangles.length);
var t = _this.triangles[tIdx];
if (!t) {
return;
}
if (t.error[3] > threshold || t.deleted || t.isDirty) {
return;
}
for (var j = 0; j < 3; ++j) {
if (t.error[j] < threshold) {
var deleted0 = [];
var deleted1 = [];
var v0 = t.vertices[j];
var v1 = t.vertices[(j + 1) % 3];
if (v0.isBorder || v1.isBorder) {
continue;
}
var p = BABYLON2.Vector3.Zero();
var n = BABYLON2.Vector3.Zero();
var uv = BABYLON2.Vector2.Zero();
var color = new BABYLON2.Color4(0, 0, 0, 1);
_this.calculateError(v0, v1, p, n, uv, color);
var delTr = new Array();
if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
continue;
}
if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
continue;
}
if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
continue;
}
var uniqueArray = new Array();
delTr.forEach(function(deletedT) {
if (uniqueArray.indexOf(deletedT) === -1) {
deletedT.deletePending = true;
uniqueArray.push(deletedT);
}
});
if (uniqueArray.length % 2 !== 0) {
continue;
}
v0.q = v1.q.add(v0.q);
v0.updatePosition(p);
var tStart = _this.references.length;
deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
var tCount = _this.references.length - tStart;
if (tCount <= v0.triangleCount) {
if (tCount) {
for (var c = 0; c < tCount; c++) {
_this.references[v0.triangleStart + c] = _this.references[tStart + c];
}
}
} else {
v0.triangleStart = tStart;
}
v0.triangleCount = tCount;
break;
}
}
};
BABYLON2.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function() {
return triangleCount - deletedTriangles <= targetCount;
});
}, 0);
};
BABYLON2.AsyncLoop.Run(this.decimationIterations, function(loop) {
if (triangleCount - deletedTriangles <= targetCount) {
loop.breakLoop();
} else {
iterationFunction(loop.index, function() {
loop.executeNext();
});
}
}, function() {
setTimeout(function() {
_this.reconstructMesh(submeshIndex);
successCallback2();
}, 0);
});
};
QuadraticErrorSimplification2.prototype.initWithMesh = function(submeshIndex, callback, optimizeMesh) {
var _this = this;
this.vertices = [];
this.triangles = [];
var positionData = this._mesh.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var indices = this._mesh.getIndices();
var submesh = this._mesh.subMeshes[submeshIndex];
var findInVertices = function(positionToSearch) {
if (optimizeMesh) {
for (var ii = 0; ii < _this.vertices.length; ++ii) {
if (_this.vertices[ii].position.equals(positionToSearch)) {
return _this.vertices[ii];
}
}
}
return null;
};
var vertexReferences = [];
var vertexInit = function(i2) {
if (!positionData) {
return;
}
var offset = i2 + submesh.verticesStart;
var position = BABYLON2.Vector3.FromArray(positionData, offset * 3);
var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
vertex.originalOffsets.push(offset);
if (vertex.id === _this.vertices.length) {
_this.vertices.push(vertex);
}
vertexReferences.push(vertex.id);
};
var totalVertices = submesh.verticesCount;
BABYLON2.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations / 4 >> 0, vertexInit, function() {
var indicesInit = function(i2) {
if (!indices) {
return;
}
var offset = submesh.indexStart / 3 + i2;
var pos = offset * 3;
var i0 = indices[pos + 0];
var i1 = indices[pos + 1];
var i22 = indices[pos + 2];
var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
var v2 = _this.vertices[vertexReferences[i22 - submesh.verticesStart]];
var triangle = new DecimationTriangle([v0, v1, v2]);
triangle.originalOffset = pos;
_this.triangles.push(triangle);
};
BABYLON2.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function() {
_this.init(callback);
});
});
};
QuadraticErrorSimplification2.prototype.init = function(callback) {
var _this = this;
var triangleInit1 = function(i2) {
var t = _this.triangles[i2];
t.normal = BABYLON2.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
for (var j = 0; j < 3; j++) {
t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -BABYLON2.Vector3.Dot(t.normal, t.vertices[0].position)));
}
};
BABYLON2.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function() {
var triangleInit2 = function(i2) {
var t = _this.triangles[i2];
for (var j = 0; j < 3; ++j) {
t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
}
t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
};
BABYLON2.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function() {
callback();
});
});
};
QuadraticErrorSimplification2.prototype.reconstructMesh = function(submeshIndex) {
var newTriangles = [];
var i2;
for (i2 = 0; i2 < this.vertices.length; ++i2) {
this.vertices[i2].triangleCount = 0;
}
var t;
var j;
for (i2 = 0; i2 < this.triangles.length; ++i2) {
if (!this.triangles[i2].deleted) {
t = this.triangles[i2];
for (j = 0; j < 3; ++j) {
t.vertices[j].triangleCount = 1;
}
newTriangles.push(t);
}
}
var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON2.VertexBuffer.PositionKind) || [];
var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON2.VertexBuffer.NormalKind) || [];
var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON2.VertexBuffer.UVKind) || [];
var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON2.VertexBuffer.ColorKind) || [];
var normalData = this._mesh.getVerticesData(BABYLON2.VertexBuffer.NormalKind);
var uvs = this._mesh.getVerticesData(BABYLON2.VertexBuffer.UVKind);
var colorsData = this._mesh.getVerticesData(BABYLON2.VertexBuffer.ColorKind);
var vertexCount = 0;
for (i2 = 0; i2 < this.vertices.length; ++i2) {
var vertex = this.vertices[i2];
vertex.id = vertexCount;
if (vertex.triangleCount) {
vertex.originalOffsets.forEach(function(originalOffset) {
if (!normalData) {
return;
}
newPositionData.push(vertex.position.x);
newPositionData.push(vertex.position.y);
newPositionData.push(vertex.position.z);
newNormalData.push(normalData[originalOffset * 3]);
newNormalData.push(normalData[originalOffset * 3 + 1]);
newNormalData.push(normalData[originalOffset * 3 + 2]);
if (uvs && uvs.length) {
newUVsData.push(uvs[originalOffset * 2]);
newUVsData.push(uvs[originalOffset * 2 + 1]);
} else if (colorsData && colorsData.length) {
newColorsData.push(colorsData[originalOffset * 4]);
newColorsData.push(colorsData[originalOffset * 4 + 1]);
newColorsData.push(colorsData[originalOffset * 4 + 2]);
newColorsData.push(colorsData[originalOffset * 4 + 3]);
}
++vertexCount;
});
}
}
var startingIndex = this._reconstructedMesh.getTotalIndices();
var startingVertex = this._reconstructedMesh.getTotalVertices();
var submeshesArray = this._reconstructedMesh.subMeshes;
this._reconstructedMesh.subMeshes = [];
var newIndicesArray = this._reconstructedMesh.getIndices();
var originalIndices = this._mesh.getIndices();
for (i2 = 0; i2 < newTriangles.length; ++i2) {
t = newTriangles[i2];
[0, 1, 2].forEach(function(idx) {
var id = originalIndices[t.originalOffset + idx];
var offset = t.vertices[idx].originalOffsets.indexOf(id);
if (offset < 0) {
offset = 0;
}
newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
});
}
this._reconstructedMesh.setIndices(newIndicesArray);
this._reconstructedMesh.setVerticesData(BABYLON2.VertexBuffer.PositionKind, newPositionData);
this._reconstructedMesh.setVerticesData(BABYLON2.VertexBuffer.NormalKind, newNormalData);
if (newUVsData.length > 0) {
this._reconstructedMesh.setVerticesData(BABYLON2.VertexBuffer.UVKind, newUVsData);
}
if (newColorsData.length > 0) {
this._reconstructedMesh.setVerticesData(BABYLON2.VertexBuffer.ColorKind, newColorsData);
}
var originalSubmesh = this._mesh.subMeshes[submeshIndex];
if (submeshIndex > 0) {
this._reconstructedMesh.subMeshes = [];
submeshesArray.forEach(function(submesh) {
BABYLON2.SubMesh.AddToMesh(
submesh.materialIndex,
submesh.verticesStart,
submesh.verticesCount,
/* 0, newPositionData.length/3, */
submesh.indexStart,
submesh.indexCount,
submesh.getMesh()
);
});
BABYLON2.SubMesh.AddToMesh(
originalSubmesh.materialIndex,
startingVertex,
vertexCount,
/* 0, newPositionData.length / 3, */
startingIndex,
newTriangles.length * 3,
this._reconstructedMesh
);
}
};
QuadraticErrorSimplification2.prototype.initDecimatedMesh = function() {
this._reconstructedMesh = new BABYLON2.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
this._reconstructedMesh.material = this._mesh.material;
this._reconstructedMesh.parent = this._mesh.parent;
this._reconstructedMesh.isVisible = false;
this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
};
QuadraticErrorSimplification2.prototype.isFlipped = function(vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
for (var i2 = 0; i2 < vertex1.triangleCount; ++i2) {
var t = this.triangles[this.references[vertex1.triangleStart + i2].triangleId];
if (t.deleted) {
continue;
}
var s = this.references[vertex1.triangleStart + i2].vertexId;
var v1 = t.vertices[(s + 1) % 3];
var v2 = t.vertices[(s + 2) % 3];
if (v1 === vertex2 || v2 === vertex2) {
deletedArray[i2] = true;
delTr.push(t);
continue;
}
var d1 = v1.position.subtract(point);
d1 = d1.normalize();
var d2 = v2.position.subtract(point);
d2 = d2.normalize();
if (Math.abs(BABYLON2.Vector3.Dot(d1, d2)) > 0.999) {
return true;
}
var normal = BABYLON2.Vector3.Cross(d1, d2).normalize();
deletedArray[i2] = false;
if (BABYLON2.Vector3.Dot(normal, t.normal) < 0.2) {
return true;
}
}
return false;
};
QuadraticErrorSimplification2.prototype.updateTriangles = function(origVertex, vertex, deletedArray, deletedTriangles) {
var newDeleted = deletedTriangles;
for (var i2 = 0; i2 < vertex.triangleCount; ++i2) {
var ref = this.references[vertex.triangleStart + i2];
var t = this.triangles[ref.triangleId];
if (t.deleted) {
continue;
}
if (deletedArray[i2] && t.deletePending) {
t.deleted = true;
newDeleted++;
continue;
}
t.vertices[ref.vertexId] = origVertex;
t.isDirty = true;
t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + t.borderFactor / 2;
t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + t.borderFactor / 2;
t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + t.borderFactor / 2;
t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
this.references.push(ref);
}
return newDeleted;
};
QuadraticErrorSimplification2.prototype.identifyBorder = function() {
for (var i2 = 0; i2 < this.vertices.length; ++i2) {
var vCount = [];
var vId = [];
var v = this.vertices[i2];
var j;
for (j = 0; j < v.triangleCount; ++j) {
var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
for (var ii = 0; ii < 3; ii++) {
var ofs = 0;
var vv = triangle.vertices[ii];
while (ofs < vCount.length) {
if (vId[ofs] === vv.id) {
break;
}
++ofs;
}
if (ofs === vCount.length) {
vCount.push(1);
vId.push(vv.id);
} else {
vCount[ofs]++;
}
}
}
for (j = 0; j < vCount.length; ++j) {
if (vCount[j] === 1) {
this.vertices[vId[j]].isBorder = true;
} else {
this.vertices[vId[j]].isBorder = false;
}
}
}
};
QuadraticErrorSimplification2.prototype.updateMesh = function(identifyBorders) {
if (identifyBorders === void 0) {
identifyBorders = false;
}
var i2;
if (!identifyBorders) {
var newTrianglesVector = [];
for (i2 = 0; i2 < this.triangles.length; ++i2) {
if (!this.triangles[i2].deleted) {
newTrianglesVector.push(this.triangles[i2]);
}
}
this.triangles = newTrianglesVector;
}
for (i2 = 0; i2 < this.vertices.length; ++i2) {
this.vertices[i2].triangleCount = 0;
this.vertices[i2].triangleStart = 0;
}
var t;
var j;
var v;
for (i2 = 0; i2 < this.triangles.length; ++i2) {
t = this.triangles[i2];
for (j = 0; j < 3; ++j) {
v = t.vertices[j];
v.triangleCount++;
}
}
var tStart = 0;
for (i2 = 0; i2 < this.vertices.length; ++i2) {
this.vertices[i2].triangleStart = tStart;
tStart += this.vertices[i2].triangleCount;
this.vertices[i2].triangleCount = 0;
}
var newReferences = new Array(this.triangles.length * 3);
for (i2 = 0; i2 < this.triangles.length; ++i2) {
t = this.triangles[i2];
for (j = 0; j < 3; ++j) {
v = t.vertices[j];
newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i2);
v.triangleCount++;
}
}
this.references = newReferences;
if (identifyBorders) {
this.identifyBorder();
}
};
QuadraticErrorSimplification2.prototype.vertexError = function(q, point) {
var x = point.x;
var y = point.y;
var z = point.z;
return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
};
QuadraticErrorSimplification2.prototype.calculateError = function(vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
var q = vertex1.q.add(vertex2.q);
var border = vertex1.isBorder && vertex2.isBorder;
var error = 0;
var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
if (qDet !== 0 && !border) {
if (!pointResult) {
pointResult = BABYLON2.Vector3.Zero();
}
pointResult.x = -1 / qDet * q.det(1, 2, 3, 4, 5, 6, 5, 7, 8);
pointResult.y = 1 / qDet * q.det(0, 2, 3, 1, 5, 6, 2, 7, 8);
pointResult.z = -1 / qDet * q.det(0, 1, 3, 1, 4, 6, 2, 5, 8);
error = this.vertexError(q, pointResult);
} else {
var p3 = vertex1.position.add(vertex2.position).divide(new BABYLON2.Vector3(2, 2, 2));
var error1 = this.vertexError(q, vertex1.position);
var error2 = this.vertexError(q, vertex2.position);
var error3 = this.vertexError(q, p3);
error = Math.min(error1, error2, error3);
if (error === error1) {
if (pointResult) {
pointResult.copyFrom(vertex1.position);
}
} else if (error === error2) {
if (pointResult) {
pointResult.copyFrom(vertex2.position);
}
} else {
if (pointResult) {
pointResult.copyFrom(p3);
}
}
}
return error;
};
return QuadraticErrorSimplification2;
}()
);
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
Object.defineProperty(BABYLON2.Scene.prototype, "simplificationQueue", {
get: function() {
if (!this._simplificationQueue) {
this._simplificationQueue = new BABYLON2.SimplificationQueue();
var component = this._getComponent(BABYLON2.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
if (!component) {
component = new SimplicationQueueSceneComponent(this);
this._addComponent(component);
}
}
return this._simplificationQueue;
},
set: function(value) {
this._simplificationQueue = value;
},
enumerable: true,
configurable: true
});
BABYLON2.Mesh.prototype.simplify = function(settings2, parallelProcessing, simplificationType, successCallback2) {
if (parallelProcessing === void 0) {
parallelProcessing = true;
}
if (simplificationType === void 0) {
simplificationType = BABYLON2.SimplificationType.QUADRATIC;
}
this.getScene().simplificationQueue.addTask({
settings: settings2,
parallelProcessing,
mesh: this,
simplificationType,
successCallback: successCallback2
});
return this;
};
var SimplicationQueueSceneComponent = (
/** @class */
function() {
function SimplicationQueueSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
this.scene = scene;
}
SimplicationQueueSceneComponent2.prototype.register = function() {
this.scene._beforeCameraUpdateStage.registerStep(BABYLON2.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
};
SimplicationQueueSceneComponent2.prototype.rebuild = function() {
};
SimplicationQueueSceneComponent2.prototype.dispose = function() {
};
SimplicationQueueSceneComponent2.prototype._beforeCameraUpdate = function() {
if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
this.scene._simplificationQueue.executeNext();
}
};
return SimplicationQueueSceneComponent2;
}()
);
BABYLON2.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var MeshLODLevel = (
/** @class */
function() {
function MeshLODLevel2(distance, mesh2) {
this.distance = distance;
this.mesh = mesh2;
}
return MeshLODLevel2;
}()
);
BABYLON2.MeshLODLevel = MeshLODLevel;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SceneOptimization = (
/** @class */
function() {
function SceneOptimization2(priority) {
if (priority === void 0) {
priority = 0;
}
this.priority = priority;
}
SceneOptimization2.prototype.getDescription = function() {
return "";
};
SceneOptimization2.prototype.apply = function(scene, optimizer2) {
return true;
};
return SceneOptimization2;
}()
);
BABYLON2.SceneOptimization = SceneOptimization;
var TextureOptimization = (
/** @class */
function(_super) {
__extends(TextureOptimization2, _super);
function TextureOptimization2(priority, maximumSize, step) {
if (priority === void 0) {
priority = 0;
}
if (maximumSize === void 0) {
maximumSize = 1024;
}
if (step === void 0) {
step = 0.5;
}
var _this = _super.call(this, priority) || this;
_this.priority = priority;
_this.maximumSize = maximumSize;
_this.step = step;
return _this;
}
TextureOptimization2.prototype.getDescription = function() {
return "Reducing render target texture size to " + this.maximumSize;
};
TextureOptimization2.prototype.apply = function(scene, optimizer2) {
var allDone = true;
for (var index = 0; index < scene.textures.length; index++) {
var texture = scene.textures[index];
if (!texture.canRescale || texture.getContext) {
continue;
}
var currentSize = texture.getSize();
var maxDimension = Math.max(currentSize.width, currentSize.height);
if (maxDimension > this.maximumSize) {
texture.scale(this.step);
allDone = false;
}
}
return allDone;
};
return TextureOptimization2;
}(SceneOptimization)
);
BABYLON2.TextureOptimization = TextureOptimization;
var HardwareScalingOptimization = (
/** @class */
function(_super) {
__extends(HardwareScalingOptimization2, _super);
function HardwareScalingOptimization2(priority, maximumScale, step) {
if (priority === void 0) {
priority = 0;
}
if (maximumScale === void 0) {
maximumScale = 2;
}
if (step === void 0) {
step = 0.25;
}
var _this = _super.call(this, priority) || this;
_this.priority = priority;
_this.maximumScale = maximumScale;
_this.step = step;
_this._currentScale = -1;
_this._directionOffset = 1;
return _this;
}
HardwareScalingOptimization2.prototype.getDescription = function() {
return "Setting hardware scaling level to " + this._currentScale;
};
HardwareScalingOptimization2.prototype.apply = function(scene, optimizer2) {
if (this._currentScale === -1) {
this._currentScale = scene.getEngine().getHardwareScalingLevel();
if (this._currentScale > this.maximumScale) {
this._directionOffset = -1;
}
}
this._currentScale += this._directionOffset * this.step;
scene.getEngine().setHardwareScalingLevel(this._currentScale);
return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
};
return HardwareScalingOptimization2;
}(SceneOptimization)
);
BABYLON2.HardwareScalingOptimization = HardwareScalingOptimization;
var ShadowsOptimization = (
/** @class */
function(_super) {
__extends(ShadowsOptimization2, _super);
function ShadowsOptimization2() {
return _super !== null && _super.apply(this, arguments) || this;
}
ShadowsOptimization2.prototype.getDescription = function() {
return "Turning shadows on/off";
};
ShadowsOptimization2.prototype.apply = function(scene, optimizer2) {
scene.shadowsEnabled = optimizer2.isInImprovementMode;
return true;
};
return ShadowsOptimization2;
}(SceneOptimization)
);
BABYLON2.ShadowsOptimization = ShadowsOptimization;
var PostProcessesOptimization = (
/** @class */
function(_super) {
__extends(PostProcessesOptimization2, _super);
function PostProcessesOptimization2() {
return _super !== null && _super.apply(this, arguments) || this;
}
PostProcessesOptimization2.prototype.getDescription = function() {
return "Turning post-processes on/off";
};
PostProcessesOptimization2.prototype.apply = function(scene, optimizer2) {
scene.postProcessesEnabled = optimizer2.isInImprovementMode;
return true;
};
return PostProcessesOptimization2;
}(SceneOptimization)
);
BABYLON2.PostProcessesOptimization = PostProcessesOptimization;
var LensFlaresOptimization = (
/** @class */
function(_super) {
__extends(LensFlaresOptimization2, _super);
function LensFlaresOptimization2() {
return _super !== null && _super.apply(this, arguments) || this;
}
LensFlaresOptimization2.prototype.getDescription = function() {
return "Turning lens flares on/off";
};
LensFlaresOptimization2.prototype.apply = function(scene, optimizer2) {
scene.lensFlaresEnabled = optimizer2.isInImprovementMode;
return true;
};
return LensFlaresOptimization2;
}(SceneOptimization)
);
BABYLON2.LensFlaresOptimization = LensFlaresOptimization;
var CustomOptimization = (
/** @class */
function(_super) {
__extends(CustomOptimization2, _super);
function CustomOptimization2() {
return _super !== null && _super.apply(this, arguments) || this;
}
CustomOptimization2.prototype.getDescription = function() {
if (this.onGetDescription) {
return this.onGetDescription();
}
return "Running user defined callback";
};
CustomOptimization2.prototype.apply = function(scene, optimizer2) {
if (this.onApply) {
return this.onApply(scene, optimizer2);
}
return true;
};
return CustomOptimization2;
}(SceneOptimization)
);
BABYLON2.CustomOptimization = CustomOptimization;
var ParticlesOptimization = (
/** @class */
function(_super) {
__extends(ParticlesOptimization2, _super);
function ParticlesOptimization2() {
return _super !== null && _super.apply(this, arguments) || this;
}
ParticlesOptimization2.prototype.getDescription = function() {
return "Turning particles on/off";
};
ParticlesOptimization2.prototype.apply = function(scene, optimizer2) {
scene.particlesEnabled = optimizer2.isInImprovementMode;
return true;
};
return ParticlesOptimization2;
}(SceneOptimization)
);
BABYLON2.ParticlesOptimization = ParticlesOptimization;
var RenderTargetsOptimization = (
/** @class */
function(_super) {
__extends(RenderTargetsOptimization2, _super);
function RenderTargetsOptimization2() {
return _super !== null && _super.apply(this, arguments) || this;
}
RenderTargetsOptimization2.prototype.getDescription = function() {
return "Turning render targets off";
};
RenderTargetsOptimization2.prototype.apply = function(scene, optimizer2) {
scene.renderTargetsEnabled = optimizer2.isInImprovementMode;
return true;
};
return RenderTargetsOptimization2;
}(SceneOptimization)
);
BABYLON2.RenderTargetsOptimization = RenderTargetsOptimization;
var MergeMeshesOptimization = (
/** @class */
function(_super) {
__extends(MergeMeshesOptimization2, _super);
function MergeMeshesOptimization2() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._canBeMerged = function(abstractMesh) {
if (!(abstractMesh instanceof BABYLON2.Mesh)) {
return false;
}
var mesh2 = abstractMesh;
if (mesh2.isDisposed()) {
return false;
}
if (!mesh2.isVisible || !mesh2.isEnabled()) {
return false;
}
if (mesh2.instances.length > 0) {
return false;
}
if (mesh2.skeleton || mesh2.hasLODLevels) {
return false;
}
return true;
};
return _this;
}
Object.defineProperty(MergeMeshesOptimization2, "UpdateSelectionTree", {
/**
* Gets or sets a boolean which defines if optimization octree has to be updated
*/
get: function() {
return MergeMeshesOptimization2._UpdateSelectionTree;
},
/**
* Gets or sets a boolean which defines if optimization octree has to be updated
*/
set: function(value) {
MergeMeshesOptimization2._UpdateSelectionTree = value;
},
enumerable: true,
configurable: true
});
MergeMeshesOptimization2.prototype.getDescription = function() {
return "Merging similar meshes together";
};
MergeMeshesOptimization2.prototype.apply = function(scene, optimizer2, updateSelectionTree) {
var globalPool = scene.meshes.slice(0);
var globalLength = globalPool.length;
for (var index = 0; index < globalLength; index++) {
var currentPool = new Array();
var current = globalPool[index];
if (!this._canBeMerged(current)) {
continue;
}
currentPool.push(current);
for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
var otherMesh = globalPool[subIndex];
if (!this._canBeMerged(otherMesh)) {
continue;
}
if (otherMesh.material !== current.material) {
continue;
}
if (otherMesh.checkCollisions !== current.checkCollisions) {
continue;
}
currentPool.push(otherMesh);
globalLength--;
globalPool.splice(subIndex, 1);
subIndex--;
}
if (currentPool.length < 2) {
continue;
}
BABYLON2.Mesh.MergeMeshes(currentPool, void 0, true);
}
var sceneAsAny = scene;
if (sceneAsAny.createOrUpdateSelectionOctree) {
if (updateSelectionTree != void 0) {
if (updateSelectionTree) {
sceneAsAny.createOrUpdateSelectionOctree();
}
} else if (MergeMeshesOptimization2.UpdateSelectionTree) {
sceneAsAny.createOrUpdateSelectionOctree();
}
}
return true;
};
MergeMeshesOptimization2._UpdateSelectionTree = false;
return MergeMeshesOptimization2;
}(SceneOptimization)
);
BABYLON2.MergeMeshesOptimization = MergeMeshesOptimization;
var SceneOptimizerOptions = (
/** @class */
function() {
function SceneOptimizerOptions2(targetFrameRate, trackerDuration) {
if (targetFrameRate === void 0) {
targetFrameRate = 60;
}
if (trackerDuration === void 0) {
trackerDuration = 2e3;
}
this.targetFrameRate = targetFrameRate;
this.trackerDuration = trackerDuration;
this.optimizations = new Array();
}
SceneOptimizerOptions2.prototype.addOptimization = function(optimization) {
this.optimizations.push(optimization);
return this;
};
SceneOptimizerOptions2.prototype.addCustomOptimization = function(onApply, onGetDescription, priority) {
if (priority === void 0) {
priority = 0;
}
var optimization = new CustomOptimization(priority);
optimization.onApply = onApply;
optimization.onGetDescription = onGetDescription;
this.optimizations.push(optimization);
return this;
};
SceneOptimizerOptions2.LowDegradationAllowed = function(targetFrameRate) {
var result = new SceneOptimizerOptions2(targetFrameRate);
var priority = 0;
result.addOptimization(new MergeMeshesOptimization(priority));
result.addOptimization(new ShadowsOptimization(priority));
result.addOptimization(new LensFlaresOptimization(priority));
priority++;
result.addOptimization(new PostProcessesOptimization(priority));
result.addOptimization(new ParticlesOptimization(priority));
priority++;
result.addOptimization(new TextureOptimization(priority, 1024));
return result;
};
SceneOptimizerOptions2.ModerateDegradationAllowed = function(targetFrameRate) {
var result = new SceneOptimizerOptions2(targetFrameRate);
var priority = 0;
result.addOptimization(new MergeMeshesOptimization(priority));
result.addOptimization(new ShadowsOptimization(priority));
result.addOptimization(new LensFlaresOptimization(priority));
priority++;
result.addOptimization(new PostProcessesOptimization(priority));
result.addOptimization(new ParticlesOptimization(priority));
priority++;
result.addOptimization(new TextureOptimization(priority, 512));
priority++;
result.addOptimization(new RenderTargetsOptimization(priority));
priority++;
result.addOptimization(new HardwareScalingOptimization(priority, 2));
return result;
};
SceneOptimizerOptions2.HighDegradationAllowed = function(targetFrameRate) {
var result = new SceneOptimizerOptions2(targetFrameRate);
var priority = 0;
result.addOptimization(new MergeMeshesOptimization(priority));
result.addOptimization(new ShadowsOptimization(priority));
result.addOptimization(new LensFlaresOptimization(priority));
priority++;
result.addOptimization(new PostProcessesOptimization(priority));
result.addOptimization(new ParticlesOptimization(priority));
priority++;
result.addOptimization(new TextureOptimization(priority, 256));
priority++;
result.addOptimization(new RenderTargetsOptimization(priority));
priority++;
result.addOptimization(new HardwareScalingOptimization(priority, 4));
return result;
};
return SceneOptimizerOptions2;
}()
);
BABYLON2.SceneOptimizerOptions = SceneOptimizerOptions;
var SceneOptimizer = (
/** @class */
function() {
function SceneOptimizer2(scene, options, autoGeneratePriorities, improvementMode) {
if (autoGeneratePriorities === void 0) {
autoGeneratePriorities = true;
}
if (improvementMode === void 0) {
improvementMode = false;
}
var _this = this;
this._isRunning = false;
this._currentPriorityLevel = 0;
this._targetFrameRate = 60;
this._trackerDuration = 2e3;
this._currentFrameRate = 0;
this._improvementMode = false;
this.onSuccessObservable = new BABYLON2.Observable();
this.onNewOptimizationAppliedObservable = new BABYLON2.Observable();
this.onFailureObservable = new BABYLON2.Observable();
if (!options) {
this._options = new SceneOptimizerOptions();
} else {
this._options = options;
}
if (this._options.targetFrameRate) {
this._targetFrameRate = this._options.targetFrameRate;
}
if (this._options.trackerDuration) {
this._trackerDuration = this._options.trackerDuration;
}
if (autoGeneratePriorities) {
var priority = 0;
for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
var optim = _a[_i];
optim.priority = priority++;
}
}
this._improvementMode = improvementMode;
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function() {
_this._sceneDisposeObserver = null;
_this.dispose();
});
}
Object.defineProperty(SceneOptimizer2.prototype, "isInImprovementMode", {
/**
* Gets a boolean indicating if the optimizer is in improvement mode
*/
get: function() {
return this._improvementMode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneOptimizer2.prototype, "currentPriorityLevel", {
/**
* Gets the current priority level (0 at start)
*/
get: function() {
return this._currentPriorityLevel;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneOptimizer2.prototype, "currentFrameRate", {
/**
* Gets the current frame rate checked by the SceneOptimizer
*/
get: function() {
return this._currentFrameRate;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneOptimizer2.prototype, "targetFrameRate", {
/**
* Gets or sets the current target frame rate (60 by default)
*/
get: function() {
return this._targetFrameRate;
},
/**
* Gets or sets the current target frame rate (60 by default)
*/
set: function(value) {
this._targetFrameRate = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneOptimizer2.prototype, "trackerDuration", {
/**
* Gets or sets the current interval between two checks (every 2000ms by default)
*/
get: function() {
return this._trackerDuration;
},
/**
* Gets or sets the current interval between two checks (every 2000ms by default)
*/
set: function(value) {
this._trackerDuration = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneOptimizer2.prototype, "optimizations", {
/**
* Gets the list of active optimizations
*/
get: function() {
return this._options.optimizations;
},
enumerable: true,
configurable: true
});
SceneOptimizer2.prototype.stop = function() {
this._isRunning = false;
};
SceneOptimizer2.prototype.reset = function() {
this._currentPriorityLevel = 0;
};
SceneOptimizer2.prototype.start = function() {
var _this = this;
if (this._isRunning) {
return;
}
this._isRunning = true;
this._scene.executeWhenReady(function() {
setTimeout(function() {
_this._checkCurrentState();
}, _this._trackerDuration);
});
};
SceneOptimizer2.prototype._checkCurrentState = function() {
var _this = this;
if (!this._isRunning) {
return;
}
var scene = this._scene;
var options = this._options;
this._currentFrameRate = Math.round(scene.getEngine().getFps());
if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate || !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
this._isRunning = false;
this.onSuccessObservable.notifyObservers(this);
return;
}
var allDone = true;
var noOptimizationApplied = true;
for (var index = 0; index < options.optimizations.length; index++) {
var optimization = options.optimizations[index];
if (optimization.priority === this._currentPriorityLevel) {
noOptimizationApplied = false;
allDone = allDone && optimization.apply(scene, this);
this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
}
}
if (noOptimizationApplied) {
this._isRunning = false;
this.onFailureObservable.notifyObservers(this);
return;
}
if (allDone) {
this._currentPriorityLevel++;
}
scene.executeWhenReady(function() {
setTimeout(function() {
_this._checkCurrentState();
}, _this._trackerDuration);
});
};
SceneOptimizer2.prototype.dispose = function() {
this.stop();
this.onSuccessObservable.clear();
this.onFailureObservable.clear();
this.onNewOptimizationAppliedObservable.clear();
if (this._sceneDisposeObserver) {
this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
}
};
SceneOptimizer2.OptimizeAsync = function(scene, options, onSuccess, onFailure) {
var optimizer2 = new SceneOptimizer2(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
if (onSuccess) {
optimizer2.onSuccessObservable.add(function() {
onSuccess();
});
}
if (onFailure) {
optimizer2.onFailureObservable.add(function() {
onFailure();
});
}
optimizer2.start();
return optimizer2;
};
return SceneOptimizer2;
}()
);
BABYLON2.SceneOptimizer = SceneOptimizer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Scene.prototype.getOutlineRenderer = function() {
if (!this._outlineRenderer) {
this._outlineRenderer = new OutlineRenderer(this);
}
return this._outlineRenderer;
};
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "renderOutline", {
get: function() {
return this._renderOutline;
},
set: function(value) {
if (value) {
this.getScene().getOutlineRenderer();
}
this._renderOutline = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "renderOverlay", {
get: function() {
return this._renderOverlay;
},
set: function(value) {
if (value) {
this.getScene().getOutlineRenderer();
}
this._renderOverlay = value;
},
enumerable: true,
configurable: true
});
var OutlineRenderer = (
/** @class */
function() {
function OutlineRenderer2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_OUTLINERENDERER;
this.zOffset = 1;
this.scene = scene;
this._engine = scene.getEngine();
this.scene._addComponent(this);
}
OutlineRenderer2.prototype.register = function() {
this.scene._beforeRenderingMeshStage.registerStep(BABYLON2.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
this.scene._afterRenderingMeshStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
};
OutlineRenderer2.prototype.rebuild = function() {
};
OutlineRenderer2.prototype.dispose = function() {
};
OutlineRenderer2.prototype.render = function(subMesh, batch, useOverlay) {
var _this = this;
if (useOverlay === void 0) {
useOverlay = false;
}
var scene = this.scene;
var engine = scene.getEngine();
var hardwareInstancedRendering = engine.getCaps().instancedArrays && batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0;
if (!this.isReady(subMesh, hardwareInstancedRendering)) {
return;
}
var mesh2 = subMesh.getRenderingMesh();
var material = subMesh.getMaterial();
if (!material || !scene.activeCamera) {
return;
}
engine.enableEffect(this._effect);
if (material.useLogarithmicDepth) {
this._effect.setFloat("logarithmicDepthConstant", 2 / (Math.log(scene.activeCamera.maxZ + 1) / Math.LN2));
}
this._effect.setFloat("offset", useOverlay ? 0 : mesh2.outlineWidth);
this._effect.setColor4("color", useOverlay ? mesh2.overlayColor : mesh2.outlineColor, useOverlay ? mesh2.overlayAlpha : material.alpha);
this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
this._effect.setMatrices("mBones", mesh2.skeleton.getTransformMatrices(mesh2));
}
mesh2._bind(subMesh, this._effect, BABYLON2.Material.TriangleFillMode);
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
this._effect.setTexture("diffuseSampler", alphaTexture);
this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
}
}
engine.setZOffset(-this.zOffset);
mesh2._processRendering(subMesh, this._effect, BABYLON2.Material.TriangleFillMode, batch, hardwareInstancedRendering, function(isInstance, world) {
_this._effect.setMatrix("world", world);
});
engine.setZOffset(0);
};
OutlineRenderer2.prototype.isReady = function(subMesh, useInstances) {
var defines = [];
var attribs = [BABYLON2.VertexBuffer.PositionKind, BABYLON2.VertexBuffer.NormalKind];
var mesh2 = subMesh.getMesh();
var material = subMesh.getMaterial();
if (material) {
if (material.needAlphaTesting()) {
defines.push("#define ALPHATEST");
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
defines.push("#define UV1");
}
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind)) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
defines.push("#define UV2");
}
}
if (material.useLogarithmicDepth) {
defines.push("#define LOGARITHMICDEPTH");
}
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (mesh2.numBoneInfluencers > 4) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
defines.push("#define BonesPerMesh " + (mesh2.skeleton ? mesh2.skeleton.bones.length + 1 : 0));
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
if (useInstances) {
defines.push("#define INSTANCES");
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
}
return this._effect.isReady();
};
OutlineRenderer2.prototype._beforeRenderingMesh = function(mesh2, subMesh, batch) {
this._savedDepthWrite = this._engine.getDepthWrite();
if (mesh2.renderOutline) {
this._engine.setDepthWrite(false);
this.render(subMesh, batch);
this._engine.setDepthWrite(this._savedDepthWrite);
}
};
OutlineRenderer2.prototype._afterRenderingMesh = function(mesh2, subMesh, batch) {
if (mesh2.renderOutline && this._savedDepthWrite) {
this._engine.setDepthWrite(true);
this._engine.setColorWrite(false);
this.render(subMesh, batch);
this._engine.setColorWrite(true);
}
if (mesh2.renderOverlay) {
var currentMode = this._engine.getAlphaMode();
this._engine.setAlphaMode(BABYLON2.Engine.ALPHA_COMBINE);
this.render(subMesh, batch, true);
this._engine.setAlphaMode(currentMode);
}
};
return OutlineRenderer2;
}()
);
BABYLON2.OutlineRenderer = OutlineRenderer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractMesh.prototype.disableEdgesRendering = function() {
if (this._edgesRenderer) {
this._edgesRenderer.dispose();
this._edgesRenderer = null;
}
return this;
};
BABYLON2.AbstractMesh.prototype.enableEdgesRendering = function(epsilon, checkVerticesInsteadOfIndices) {
if (epsilon === void 0) {
epsilon = 0.95;
}
if (checkVerticesInsteadOfIndices === void 0) {
checkVerticesInsteadOfIndices = false;
}
this.disableEdgesRendering();
this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
return this;
};
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "edgesRenderer", {
get: function() {
return this._edgesRenderer;
},
enumerable: true,
configurable: true
});
BABYLON2.LinesMesh.prototype.enableEdgesRendering = function(epsilon, checkVerticesInsteadOfIndices) {
if (epsilon === void 0) {
epsilon = 0.95;
}
if (checkVerticesInsteadOfIndices === void 0) {
checkVerticesInsteadOfIndices = false;
}
this.disableEdgesRendering();
this._edgesRenderer = new BABYLON2.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
return this;
};
var FaceAdjacencies = (
/** @class */
function() {
function FaceAdjacencies2() {
this.edges = new Array();
this.edgesConnectedCount = 0;
}
return FaceAdjacencies2;
}()
);
var EdgesRenderer = (
/** @class */
function() {
function EdgesRenderer2(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
if (epsilon === void 0) {
epsilon = 0.95;
}
if (checkVerticesInsteadOfIndices === void 0) {
checkVerticesInsteadOfIndices = false;
}
if (generateEdgesLines === void 0) {
generateEdgesLines = true;
}
var _this = this;
this.edgesWidthScalerForOrthographic = 1e3;
this.edgesWidthScalerForPerspective = 50;
this._linesPositions = new Array();
this._linesNormals = new Array();
this._linesIndices = new Array();
this._buffers = {};
this._checkVerticesInsteadOfIndices = false;
this.isEnabled = true;
this._source = source;
this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
this._epsilon = epsilon;
this._prepareRessources();
if (generateEdgesLines) {
this._generateEdgesLines();
}
this._meshRebuildObserver = this._source.onRebuildObservable.add(function() {
_this._rebuild();
});
this._meshDisposeObserver = this._source.onDisposeObservable.add(function() {
_this.dispose();
});
}
EdgesRenderer2.prototype._prepareRessources = function() {
if (this._lineShader) {
return;
}
this._lineShader = new BABYLON2.ShaderMaterial("lineShader", this._source.getScene(), "line", {
attributes: ["position", "normal"],
uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
});
this._lineShader.disableDepthWrite = true;
this._lineShader.backFaceCulling = false;
};
EdgesRenderer2.prototype._rebuild = function() {
var buffer = this._buffers[BABYLON2.VertexBuffer.PositionKind];
if (buffer) {
buffer._rebuild();
}
buffer = this._buffers[BABYLON2.VertexBuffer.NormalKind];
if (buffer) {
buffer._rebuild();
}
var scene = this._source.getScene();
var engine = scene.getEngine();
this._ib = engine.createIndexBuffer(this._linesIndices);
};
EdgesRenderer2.prototype.dispose = function() {
this._source.onRebuildObservable.remove(this._meshRebuildObserver);
this._source.onDisposeObservable.remove(this._meshDisposeObserver);
var buffer = this._buffers[BABYLON2.VertexBuffer.PositionKind];
if (buffer) {
buffer.dispose();
this._buffers[BABYLON2.VertexBuffer.PositionKind] = null;
}
buffer = this._buffers[BABYLON2.VertexBuffer.NormalKind];
if (buffer) {
buffer.dispose();
this._buffers[BABYLON2.VertexBuffer.NormalKind] = null;
}
this._source.getScene().getEngine()._releaseBuffer(this._ib);
this._lineShader.dispose();
};
EdgesRenderer2.prototype._processEdgeForAdjacencies = function(pa, pb, p0, p1, p2) {
if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
return 0;
}
if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
return 1;
}
if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
return 2;
}
return -1;
};
EdgesRenderer2.prototype._processEdgeForAdjacenciesWithVertices = function(pa, pb, p0, p1, p2) {
if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
return 0;
}
if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
return 1;
}
if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
return 2;
}
return -1;
};
EdgesRenderer2.prototype._checkEdge = function(faceIndex, edge, faceNormals, p0, p1) {
var needToCreateLine;
if (edge === void 0) {
needToCreateLine = true;
} else {
var dotProduct = BABYLON2.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
needToCreateLine = dotProduct < this._epsilon;
}
if (needToCreateLine) {
var offset = this._linesPositions.length / 3;
var normal = p0.subtract(p1);
normal.normalize();
this._linesPositions.push(p0.x);
this._linesPositions.push(p0.y);
this._linesPositions.push(p0.z);
this._linesPositions.push(p0.x);
this._linesPositions.push(p0.y);
this._linesPositions.push(p0.z);
this._linesPositions.push(p1.x);
this._linesPositions.push(p1.y);
this._linesPositions.push(p1.z);
this._linesPositions.push(p1.x);
this._linesPositions.push(p1.y);
this._linesPositions.push(p1.z);
this._linesNormals.push(p1.x);
this._linesNormals.push(p1.y);
this._linesNormals.push(p1.z);
this._linesNormals.push(-1);
this._linesNormals.push(p1.x);
this._linesNormals.push(p1.y);
this._linesNormals.push(p1.z);
this._linesNormals.push(1);
this._linesNormals.push(p0.x);
this._linesNormals.push(p0.y);
this._linesNormals.push(p0.z);
this._linesNormals.push(-1);
this._linesNormals.push(p0.x);
this._linesNormals.push(p0.y);
this._linesNormals.push(p0.z);
this._linesNormals.push(1);
this._linesIndices.push(offset);
this._linesIndices.push(offset + 1);
this._linesIndices.push(offset + 2);
this._linesIndices.push(offset);
this._linesIndices.push(offset + 2);
this._linesIndices.push(offset + 3);
}
};
EdgesRenderer2.prototype._generateEdgesLines = function() {
var positions = this._source.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var indices = this._source.getIndices();
if (!indices || !positions) {
return;
}
var adjacencies = new Array();
var faceNormals = new Array();
var index;
var faceAdjacencies;
for (index = 0; index < indices.length; index += 3) {
faceAdjacencies = new FaceAdjacencies();
var p0Index = indices[index];
var p1Index = indices[index + 1];
var p2Index = indices[index + 2];
faceAdjacencies.p0 = new BABYLON2.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
faceAdjacencies.p1 = new BABYLON2.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
faceAdjacencies.p2 = new BABYLON2.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
var faceNormal = BABYLON2.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
faceNormal.normalize();
faceNormals.push(faceNormal);
adjacencies.push(faceAdjacencies);
}
for (index = 0; index < adjacencies.length; index++) {
faceAdjacencies = adjacencies[index];
for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
var otherFaceAdjacencies = adjacencies[otherIndex];
if (faceAdjacencies.edgesConnectedCount === 3) {
break;
}
if (otherFaceAdjacencies.edgesConnectedCount === 3) {
continue;
}
var otherP0 = indices[otherIndex * 3];
var otherP1 = indices[otherIndex * 3 + 1];
var otherP2 = indices[otherIndex * 3 + 2];
for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
var otherEdgeIndex = 0;
if (faceAdjacencies.edges[edgeIndex] !== void 0) {
continue;
}
switch (edgeIndex) {
case 0:
if (this._checkVerticesInsteadOfIndices) {
otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
} else {
otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
}
break;
case 1:
if (this._checkVerticesInsteadOfIndices) {
otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
} else {
otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
}
break;
case 2:
if (this._checkVerticesInsteadOfIndices) {
otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
} else {
otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
}
break;
}
if (otherEdgeIndex === -1) {
continue;
}
faceAdjacencies.edges[edgeIndex] = otherIndex;
otherFaceAdjacencies.edges[otherEdgeIndex] = index;
faceAdjacencies.edgesConnectedCount++;
otherFaceAdjacencies.edgesConnectedCount++;
if (faceAdjacencies.edgesConnectedCount === 3) {
break;
}
}
}
}
for (index = 0; index < adjacencies.length; index++) {
var current = adjacencies[index];
this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
}
var engine = this._source.getScene().getEngine();
this._buffers[BABYLON2.VertexBuffer.PositionKind] = new BABYLON2.VertexBuffer(engine, this._linesPositions, BABYLON2.VertexBuffer.PositionKind, false);
this._buffers[BABYLON2.VertexBuffer.NormalKind] = new BABYLON2.VertexBuffer(engine, this._linesNormals, BABYLON2.VertexBuffer.NormalKind, false, false, 4);
this._ib = engine.createIndexBuffer(this._linesIndices);
this._indicesCount = this._linesIndices.length;
};
EdgesRenderer2.prototype.isReady = function() {
return this._lineShader.isReady();
};
EdgesRenderer2.prototype.render = function() {
var scene = this._source.getScene();
if (!this.isReady() || !scene.activeCamera) {
return;
}
var engine = scene.getEngine();
this._lineShader._preBind();
if (this._source.edgesColor.a !== 1) {
engine.setAlphaMode(BABYLON2.Engine.ALPHA_COMBINE);
} else {
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
}
engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
scene.resetCachedMaterial();
this._lineShader.setColor4("color", this._source.edgesColor);
if (scene.activeCamera.mode === BABYLON2.Camera.ORTHOGRAPHIC_CAMERA) {
this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
} else {
this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
}
this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
this._lineShader.bind(this._source.getWorldMatrix());
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, this._indicesCount);
this._lineShader.unbind();
};
return EdgesRenderer2;
}()
);
BABYLON2.EdgesRenderer = EdgesRenderer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FaceAdjacencies = (
/** @class */
function() {
function FaceAdjacencies2() {
this.edges = new Array();
this.edgesConnectedCount = 0;
}
return FaceAdjacencies2;
}()
);
var LineEdgesRenderer = (
/** @class */
function(_super) {
__extends(LineEdgesRenderer2, _super);
function LineEdgesRenderer2(source, epsilon, checkVerticesInsteadOfIndices) {
if (epsilon === void 0) {
epsilon = 0.95;
}
if (checkVerticesInsteadOfIndices === void 0) {
checkVerticesInsteadOfIndices = false;
}
var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
_this._generateEdgesLines();
return _this;
}
LineEdgesRenderer2.prototype._checkEdge = function(faceIndex, edge, faceNormals, p0, p1) {
var offset = this._linesPositions.length / 3;
var normal = p0.subtract(p1);
normal.normalize();
this._linesPositions.push(p0.x);
this._linesPositions.push(p0.y);
this._linesPositions.push(p0.z);
this._linesPositions.push(p0.x);
this._linesPositions.push(p0.y);
this._linesPositions.push(p0.z);
this._linesPositions.push(p1.x);
this._linesPositions.push(p1.y);
this._linesPositions.push(p1.z);
this._linesPositions.push(p1.x);
this._linesPositions.push(p1.y);
this._linesPositions.push(p1.z);
this._linesNormals.push(p1.x);
this._linesNormals.push(p1.y);
this._linesNormals.push(p1.z);
this._linesNormals.push(-1);
this._linesNormals.push(p1.x);
this._linesNormals.push(p1.y);
this._linesNormals.push(p1.z);
this._linesNormals.push(1);
this._linesNormals.push(p0.x);
this._linesNormals.push(p0.y);
this._linesNormals.push(p0.z);
this._linesNormals.push(-1);
this._linesNormals.push(p0.x);
this._linesNormals.push(p0.y);
this._linesNormals.push(p0.z);
this._linesNormals.push(1);
this._linesIndices.push(offset);
this._linesIndices.push(offset + 1);
this._linesIndices.push(offset + 2);
this._linesIndices.push(offset);
this._linesIndices.push(offset + 2);
this._linesIndices.push(offset + 3);
};
LineEdgesRenderer2.prototype._generateEdgesLines = function() {
var positions = this._source.getVerticesData(BABYLON2.VertexBuffer.PositionKind);
var indices = this._source.getIndices();
if (!indices || !positions) {
return;
}
var adjacencies = new Array();
var faceNormals = new Array();
var index;
for (var i2 = 0; i2 < positions.length / 3 - 1; i2++) {
var currentAdjecancy = new FaceAdjacencies();
currentAdjecancy.p0 = new BABYLON2.Vector3(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2]);
currentAdjecancy.p1 = new BABYLON2.Vector3(positions[(i2 + 1) * 3], positions[(i2 + 1) * 3 + 1], positions[(i2 + 1) * 3 + 2]);
adjacencies.push(currentAdjecancy);
}
for (index = 0; index < adjacencies.length; index++) {
var current = adjacencies[index];
this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
}
var engine = this._source.getScene().getEngine();
this._buffers[BABYLON2.VertexBuffer.PositionKind] = new BABYLON2.VertexBuffer(engine, this._linesPositions, BABYLON2.VertexBuffer.PositionKind, false);
this._buffers[BABYLON2.VertexBuffer.NormalKind] = new BABYLON2.VertexBuffer(engine, this._linesNormals, BABYLON2.VertexBuffer.NormalKind, false, false, 4);
this._ib = engine.createIndexBuffer(this._linesIndices);
this._indicesCount = this._linesIndices.length;
};
return LineEdgesRenderer2;
}(BABYLON2.EdgesRenderer)
);
BABYLON2.LineEdgesRenderer = LineEdgesRenderer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractScene.AddParser(BABYLON2.SceneComponentConstants.NAME_EFFECTLAYER, function(parsedData, scene, container, rootUrl) {
if (parsedData.effectLayers) {
if (!container.effectLayers) {
container.effectLayers = new Array();
}
for (var index = 0; index < parsedData.effectLayers.length; index++) {
var effectLayer = BABYLON2.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
container.effectLayers.push(effectLayer);
}
}
});
BABYLON2.AbstractScene.prototype.removeEffectLayer = function(toRemove) {
var index = this.effectLayers.indexOf(toRemove);
if (index !== -1) {
this.effectLayers.splice(index, 1);
}
return index;
};
BABYLON2.AbstractScene.prototype.addEffectLayer = function(newEffectLayer) {
this.effectLayers.push(newEffectLayer);
};
var EffectLayerSceneComponent = (
/** @class */
function() {
function EffectLayerSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_EFFECTLAYER;
this._renderEffects = false;
this._needStencil = false;
this._previousStencilState = false;
this.scene = scene;
this._engine = scene.getEngine();
scene.effectLayers = new Array();
}
EffectLayerSceneComponent2.prototype.register = function() {
this.scene._isReadyForMeshStage.registerStep(BABYLON2.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON2.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
this.scene._beforeCameraDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
this.scene._afterCameraDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
this.scene._afterCameraDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
};
EffectLayerSceneComponent2.prototype.rebuild = function() {
var layers = this.scene.effectLayers;
for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
var effectLayer = layers_1[_i];
effectLayer._rebuild();
}
};
EffectLayerSceneComponent2.prototype.serialize = function(serializationObject) {
serializationObject.effectLayers = [];
var layers = this.scene.effectLayers;
for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
var effectLayer = layers_2[_i];
if (effectLayer.serialize) {
serializationObject.effectLayers.push(effectLayer.serialize());
}
}
};
EffectLayerSceneComponent2.prototype.addFromContainer = function(container) {
var _this = this;
if (!container.effectLayers) {
return;
}
container.effectLayers.forEach(function(o) {
_this.scene.addEffectLayer(o);
});
};
EffectLayerSceneComponent2.prototype.removeFromContainer = function(container) {
var _this = this;
if (!container.effectLayers) {
return;
}
container.effectLayers.forEach(function(o) {
_this.scene.removeEffectLayer(o);
});
};
EffectLayerSceneComponent2.prototype.dispose = function() {
var layers = this.scene.effectLayers;
while (layers.length) {
layers[0].dispose();
}
};
EffectLayerSceneComponent2.prototype._isReadyForMesh = function(mesh2, hardwareInstancedRendering) {
var layers = this.scene.effectLayers;
for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
var layer = layers_3[_i];
if (!layer.hasMesh(mesh2)) {
continue;
}
for (var _a = 0, _b = mesh2.subMeshes; _a < _b.length; _a++) {
var subMesh = _b[_a];
if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
return false;
}
}
}
return true;
};
EffectLayerSceneComponent2.prototype._renderMainTexture = function(camera2) {
this._renderEffects = false;
this._needStencil = false;
var layers = this.scene.effectLayers;
if (layers && layers.length > 0) {
this._previousStencilState = this._engine.getStencilBuffer();
for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
var effectLayer = layers_4[_i];
if (effectLayer.shouldRender() && (!effectLayer.camera || effectLayer.camera.cameraRigMode === BABYLON2.Camera.RIG_MODE_NONE && camera2 === effectLayer.camera || effectLayer.camera.cameraRigMode !== BABYLON2.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera2) > -1)) {
this._renderEffects = true;
this._needStencil = this._needStencil || effectLayer.needStencil();
var renderTarget = effectLayer._mainTexture;
if (renderTarget._shouldRender()) {
this.scene.incrementRenderId();
renderTarget.render(false, false);
}
}
}
this.scene.incrementRenderId();
}
};
EffectLayerSceneComponent2.prototype._setStencil = function(camera2) {
if (this._needStencil) {
this._engine.setStencilBuffer(true);
}
};
EffectLayerSceneComponent2.prototype._setStencilBack = function(camera2) {
if (this._needStencil) {
this._engine.setStencilBuffer(this._previousStencilState);
}
};
EffectLayerSceneComponent2.prototype._draw = function(renderingGroupId) {
if (this._renderEffects) {
this._engine.setDepthBuffer(false);
var layers = this.scene.effectLayers;
for (var i2 = 0; i2 < layers.length; i2++) {
var effectLayer = layers[i2];
if (effectLayer.renderingGroupId === renderingGroupId) {
if (effectLayer.shouldRender()) {
effectLayer.render();
}
}
}
this._engine.setDepthBuffer(true);
}
};
EffectLayerSceneComponent2.prototype._drawCamera = function(camera2) {
if (this._renderEffects) {
this._draw(-1);
}
};
EffectLayerSceneComponent2.prototype._drawRenderingGroup = function(index) {
if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
this._draw(index);
}
};
return EffectLayerSceneComponent2;
}()
);
BABYLON2.EffectLayerSceneComponent = EffectLayerSceneComponent;
})(BABYLON || (BABYLON = {}));
var __assign = function() {
__assign = Object.assign || function(t) {
for (var s, i2 = 1, n = arguments.length; i2 < n; i2++) {
s = arguments[i2];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var BABYLON;
(function(BABYLON2) {
var EffectLayer = (
/** @class */
function() {
function EffectLayer2(name, scene) {
this._vertexBuffers = {};
this._maxSize = 0;
this._mainTextureDesiredSize = { width: 0, height: 0 };
this._shouldRender = true;
this._postProcesses = [];
this._textures = [];
this._emissiveTextureAndColor = { texture: null, color: new BABYLON2.Color4() };
this.neutralColor = new BABYLON2.Color4();
this.isEnabled = true;
this.onDisposeObservable = new BABYLON2.Observable();
this.onBeforeRenderMainTextureObservable = new BABYLON2.Observable();
this.onBeforeComposeObservable = new BABYLON2.Observable();
this.onAfterComposeObservable = new BABYLON2.Observable();
this.onSizeChangedObservable = new BABYLON2.Observable();
this.name = name;
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
var component = this._scene._getComponent(BABYLON2.SceneComponentConstants.NAME_EFFECTLAYER);
if (!component) {
component = new BABYLON2.EffectLayerSceneComponent(this._scene);
this._scene._addComponent(component);
}
this._engine = this._scene.getEngine();
this._maxSize = this._engine.getCaps().maxTextureSize;
this._scene.effectLayers.push(this);
this._generateIndexBuffer();
this._genrateVertexBuffer();
}
Object.defineProperty(EffectLayer2.prototype, "camera", {
/**
* Gets the camera attached to the layer.
*/
get: function() {
return this._effectLayerOptions.camera;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EffectLayer2.prototype, "renderingGroupId", {
/**
* Gets the rendering group id the layer should render in.
*/
get: function() {
return this._effectLayerOptions.renderingGroupId;
},
enumerable: true,
configurable: true
});
EffectLayer2.prototype._init = function(options) {
this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON2.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
this._setMainTextureSize();
this._createMainTexture();
this._createTextureAndPostProcesses();
this._mergeEffect = this._createMergeEffect();
};
EffectLayer2.prototype._generateIndexBuffer = function() {
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = this._engine.createIndexBuffer(indices);
};
EffectLayer2.prototype._genrateVertexBuffer = function() {
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
var vertexBuffer = new BABYLON2.VertexBuffer(this._engine, vertices, BABYLON2.VertexBuffer.PositionKind, false, false, 2);
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = vertexBuffer;
};
EffectLayer2.prototype._setMainTextureSize = function() {
if (this._effectLayerOptions.mainTextureFixedSize) {
this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
} else {
this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
}
this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
};
EffectLayer2.prototype._createMainTexture = function() {
var _this = this;
this._mainTexture = new BABYLON2.RenderTargetTexture("HighlightLayerMainRTT", {
width: this._mainTextureDesiredSize.width,
height: this._mainTextureDesiredSize.height
}, this._scene, false, true, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
this._mainTexture.activeCamera = this._effectLayerOptions.camera;
this._mainTexture.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._mainTexture.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._mainTexture.anisotropicFilteringLevel = 1;
this._mainTexture.updateSamplingMode(BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
this._mainTexture.renderParticles = false;
this._mainTexture.renderList = null;
this._mainTexture.ignoreCameraViewport = true;
this._mainTexture.customRenderFunction = function(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
_this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
var index;
var engine = _this._scene.getEngine();
if (depthOnlySubMeshes.length) {
engine.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
_this._renderSubMesh(depthOnlySubMeshes.data[index]);
}
engine.setColorWrite(true);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
_this._renderSubMesh(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
_this._renderSubMesh(alphaTestSubMeshes.data[index]);
}
for (index = 0; index < transparentSubMeshes.length; index++) {
_this._renderSubMesh(transparentSubMeshes.data[index]);
}
};
this._mainTexture.onClearObservable.add(function(engine) {
engine.clear(_this.neutralColor, true, true, true);
});
};
EffectLayer2.prototype._isReady = function(subMesh, useInstances, emissiveTexture) {
var material = subMesh.getMaterial();
if (!material) {
return false;
}
if (!material.isReady(subMesh.getMesh(), useInstances)) {
return false;
}
var defines = [];
var attribs = [BABYLON2.VertexBuffer.PositionKind];
var mesh2 = subMesh.getMesh();
var uv1 = false;
var uv2 = false;
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
defines.push("#define ALPHATEST");
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind) && alphaTexture.coordinatesIndex === 1) {
defines.push("#define DIFFUSEUV2");
uv2 = true;
} else if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
defines.push("#define DIFFUSEUV1");
uv1 = true;
}
}
}
if (emissiveTexture) {
defines.push("#define EMISSIVE");
if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) {
defines.push("#define EMISSIVEUV2");
uv2 = true;
} else if (mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.UVKind)) {
defines.push("#define EMISSIVEUV1");
uv1 = true;
}
}
if (uv1) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
defines.push("#define UV1");
}
if (uv2) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
defines.push("#define UV2");
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsKind);
if (mesh2.numBoneInfluencers > 4) {
attribs.push(BABYLON2.VertexBuffer.MatricesIndicesExtraKind);
attribs.push(BABYLON2.VertexBuffer.MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh2.numBoneInfluencers);
defines.push("#define BonesPerMesh " + (mesh2.skeleton ? mesh2.skeleton.bones.length + 1 : 0));
} else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
var manager = mesh2.morphTargetManager;
var morphInfluencers = 0;
if (manager) {
if (manager.numInfluencers > 0) {
defines.push("#define MORPHTARGETS");
morphInfluencers = manager.numInfluencers;
defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
BABYLON2.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh2, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
}
}
if (useInstances) {
defines.push("#define INSTANCES");
attribs.push("world0");
attribs.push("world1");
attribs.push("world2");
attribs.push("world3");
}
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, void 0, void 0, void 0, { maxSimultaneousMorphTargets: morphInfluencers });
}
return this._effectLayerMapGenerationEffect.isReady();
};
EffectLayer2.prototype.render = function() {
var currentEffect = this._mergeEffect;
if (!currentEffect.isReady()) {
return;
}
for (var i2 = 0; i2 < this._postProcesses.length; i2++) {
if (!this._postProcesses[i2].isReady()) {
return;
}
}
var engine = this._scene.getEngine();
this.onBeforeComposeObservable.notifyObservers(this);
engine.enableEffect(currentEffect);
engine.setState(false);
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
var previousAlphaMode = engine.getAlphaMode();
engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
this._internalRender(currentEffect);
engine.setAlphaMode(previousAlphaMode);
this.onAfterComposeObservable.notifyObservers(this);
var size = this._mainTexture.getSize();
this._setMainTextureSize();
if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
this.onSizeChangedObservable.notifyObservers(this);
this._disposeTextureAndPostProcesses();
this._createMainTexture();
this._createTextureAndPostProcesses();
}
};
EffectLayer2.prototype.hasMesh = function(mesh2) {
if (this.renderingGroupId === -1 || mesh2.renderingGroupId === this.renderingGroupId) {
return true;
}
return false;
};
EffectLayer2.prototype.shouldRender = function() {
return this.isEnabled && this._shouldRender;
};
EffectLayer2.prototype._shouldRenderMesh = function(mesh2) {
return true;
};
EffectLayer2.prototype._shouldRenderEmissiveTextureForMesh = function(mesh2) {
return true;
};
EffectLayer2.prototype._renderSubMesh = function(subMesh) {
var _this = this;
if (!this.shouldRender()) {
return;
}
var material = subMesh.getMaterial();
var mesh2 = subMesh.getRenderingMesh();
var scene = this._scene;
var engine = scene.getEngine();
if (!material) {
return;
}
if (material.needAlphaBlendingForMesh(mesh2)) {
return;
}
engine.setState(material.backFaceCulling);
var batch = mesh2._getInstancesRenderList(subMesh._id);
if (batch.mustReturn) {
return;
}
if (!this._shouldRenderMesh(mesh2)) {
return;
}
var hardwareInstancedRendering = engine.getCaps().instancedArrays && batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0;
this._setEmissiveTextureAndColor(mesh2, subMesh, material);
if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
engine.enableEffect(this._effectLayerMapGenerationEffect);
mesh2._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON2.Material.TriangleFillMode);
this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
var textureMatrix = alphaTexture.getTextureMatrix();
if (textureMatrix) {
this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
}
}
}
if (this._emissiveTextureAndColor.texture) {
this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
}
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh2.skeleton.getTransformMatrices(mesh2));
}
BABYLON2.MaterialHelper.BindMorphTargetParameters(mesh2, this._effectLayerMapGenerationEffect);
mesh2._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON2.Material.TriangleFillMode, batch, hardwareInstancedRendering, function(isInstance, world) {
return _this._effectLayerMapGenerationEffect.setMatrix("world", world);
});
} else {
this._mainTexture.resetRefreshCounter();
}
};
EffectLayer2.prototype._rebuild = function() {
var vb = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vb) {
vb._rebuild();
}
this._generateIndexBuffer();
};
EffectLayer2.prototype._disposeTextureAndPostProcesses = function() {
this._mainTexture.dispose();
for (var i2 = 0; i2 < this._postProcesses.length; i2++) {
if (this._postProcesses[i2]) {
this._postProcesses[i2].dispose();
}
}
this._postProcesses = [];
for (var i2 = 0; i2 < this._textures.length; i2++) {
if (this._textures[i2]) {
this._textures[i2].dispose();
}
}
this._textures = [];
};
EffectLayer2.prototype.dispose = function() {
var vertexBuffer = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
this._disposeTextureAndPostProcesses();
var index = this._scene.effectLayers.indexOf(this, 0);
if (index > -1) {
this._scene.effectLayers.splice(index, 1);
}
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onBeforeRenderMainTextureObservable.clear();
this.onBeforeComposeObservable.clear();
this.onAfterComposeObservable.clear();
this.onSizeChangedObservable.clear();
};
EffectLayer2.prototype.getClassName = function() {
return "EffectLayer";
};
EffectLayer2.Parse = function(parsedEffectLayer, scene, rootUrl) {
var effectLayerType = BABYLON2.Tools.Instantiate(parsedEffectLayer.customType);
return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
};
__decorate([
BABYLON2.serialize()
], EffectLayer2.prototype, "name", void 0);
__decorate([
BABYLON2.serializeAsColor4()
], EffectLayer2.prototype, "neutralColor", void 0);
__decorate([
BABYLON2.serialize()
], EffectLayer2.prototype, "isEnabled", void 0);
__decorate([
BABYLON2.serializeAsCameraReference()
], EffectLayer2.prototype, "camera", null);
__decorate([
BABYLON2.serialize()
], EffectLayer2.prototype, "renderingGroupId", null);
return EffectLayer2;
}()
);
BABYLON2.EffectLayer = EffectLayer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractScene.prototype.getHighlightLayerByName = function(name) {
for (var index = 0; index < this.effectLayers.length; index++) {
if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
return this.effectLayers[index];
}
}
return null;
};
var GlowBlurPostProcess = (
/** @class */
function(_super) {
__extends(GlowBlurPostProcess2, _super);
function GlowBlurPostProcess2(name, direction, kernel, options, camera2, samplingMode, engine, reusable) {
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.BILINEAR_SAMPLINGMODE;
}
var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera2, samplingMode, engine, reusable) || this;
_this.direction = direction;
_this.kernel = kernel;
_this.onApplyObservable.add(function(effect) {
effect.setFloat2("screenSize", _this.width, _this.height);
effect.setVector2("direction", _this.direction);
effect.setFloat("blurWidth", _this.kernel);
});
return _this;
}
return GlowBlurPostProcess2;
}(BABYLON2.PostProcess)
);
var HighlightLayer = (
/** @class */
function(_super) {
__extends(HighlightLayer2, _super);
function HighlightLayer2(name, scene, options) {
var _this = _super.call(this, name, scene) || this;
_this.name = name;
_this.innerGlow = true;
_this.outerGlow = true;
_this.onBeforeBlurObservable = new BABYLON2.Observable();
_this.onAfterBlurObservable = new BABYLON2.Observable();
_this._instanceGlowingMeshStencilReference = HighlightLayer2.GlowingMeshStencilReference++;
_this._meshes = {};
_this._excludedMeshes = {};
_this.neutralColor = HighlightLayer2.NeutralColor;
if (!_this._engine.isStencilEnable) {
BABYLON2.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
}
_this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1, blurVerticalSize: 1, alphaBlendingMode: BABYLON2.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
_this._init({
alphaBlendingMode: _this._options.alphaBlendingMode,
camera: _this._options.camera,
mainTextureFixedSize: _this._options.mainTextureFixedSize,
mainTextureRatio: _this._options.mainTextureRatio,
renderingGroupId: _this._options.renderingGroupId
});
_this._shouldRender = false;
return _this;
}
Object.defineProperty(HighlightLayer2.prototype, "blurHorizontalSize", {
/**
* Gets the horizontal size of the blur.
*/
get: function() {
return this._horizontalBlurPostprocess.kernel;
},
/**
* Specifies the horizontal size of the blur.
*/
set: function(value) {
this._horizontalBlurPostprocess.kernel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HighlightLayer2.prototype, "blurVerticalSize", {
/**
* Gets the vertical size of the blur.
*/
get: function() {
return this._verticalBlurPostprocess.kernel;
},
/**
* Specifies the vertical size of the blur.
*/
set: function(value) {
this._verticalBlurPostprocess.kernel = value;
},
enumerable: true,
configurable: true
});
HighlightLayer2.prototype.getEffectName = function() {
return HighlightLayer2.EffectName;
};
HighlightLayer2.prototype._createMergeEffect = function() {
return this._engine.createEffect("glowMapMerge", [BABYLON2.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : void 0);
};
HighlightLayer2.prototype._createTextureAndPostProcesses = function() {
var _this = this;
var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
blurTextureWidth = this._engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
blurTextureHeight = this._engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
var textureType = 0;
if (this._engine.getCaps().textureHalfFloatRender) {
textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
} else {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
this._blurTexture = new BABYLON2.RenderTargetTexture("HighlightLayerBlurRTT", {
width: blurTextureWidth,
height: blurTextureHeight
}, this._scene, false, true, textureType);
this._blurTexture.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._blurTexture.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._blurTexture.anisotropicFilteringLevel = 16;
this._blurTexture.updateSamplingMode(BABYLON2.Texture.TRILINEAR_SAMPLINGMODE);
this._blurTexture.renderParticles = false;
this._blurTexture.ignoreCameraViewport = true;
this._textures = [this._blurTexture];
if (this._options.alphaBlendingMode === BABYLON2.Engine.ALPHA_COMBINE) {
this._downSamplePostprocess = new BABYLON2.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
this._downSamplePostprocess.onApplyObservable.add(function(effect) {
effect.setTexture("textureSampler", _this._mainTexture);
});
this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON2.Vector2(1, 0), this._options.blurHorizontalSize, 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
this._horizontalBlurPostprocess.onApplyObservable.add(function(effect) {
effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
});
this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON2.Vector2(0, 1), this._options.blurVerticalSize, 1, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
this._verticalBlurPostprocess.onApplyObservable.add(function(effect) {
effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
});
this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
} else {
this._horizontalBlurPostprocess = new BABYLON2.BlurPostProcess("HighlightLayerHBP", new BABYLON2.Vector2(1, 0), this._options.blurHorizontalSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess.width = blurTextureWidth;
this._horizontalBlurPostprocess.height = blurTextureHeight;
this._horizontalBlurPostprocess.onApplyObservable.add(function(effect) {
effect.setTexture("textureSampler", _this._mainTexture);
});
this._verticalBlurPostprocess = new BABYLON2.BlurPostProcess("HighlightLayerVBP", new BABYLON2.Vector2(0, 1), this._options.blurVerticalSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
}
this._mainTexture.onAfterUnbindObservable.add(function() {
_this.onBeforeBlurObservable.notifyObservers(_this);
var internalTexture = _this._blurTexture.getInternalTexture();
if (internalTexture) {
_this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
}
_this.onAfterBlurObservable.notifyObservers(_this);
});
this._postProcesses.map(function(pp) {
pp.autoClear = false;
});
};
HighlightLayer2.prototype.needStencil = function() {
return true;
};
HighlightLayer2.prototype.isReady = function(subMesh, useInstances) {
var material = subMesh.getMaterial();
var mesh2 = subMesh.getRenderingMesh();
if (!material || !mesh2 || !this._meshes) {
return false;
}
var emissiveTexture = null;
var highlightLayerMesh = this._meshes[mesh2.uniqueId];
if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
emissiveTexture = material.emissiveTexture;
}
return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
};
HighlightLayer2.prototype._internalRender = function(effect) {
effect.setTexture("textureSampler", this._blurTexture);
var engine = this._engine;
var previousStencilBuffer = engine.getStencilBuffer();
var previousStencilFunction = engine.getStencilFunction();
var previousStencilMask = engine.getStencilMask();
var previousStencilOperationPass = engine.getStencilOperationPass();
var previousStencilOperationFail = engine.getStencilOperationFail();
var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
var previousStencilReference = engine.getStencilFunctionReference();
engine.setStencilOperationPass(BABYLON2.Engine.REPLACE);
engine.setStencilOperationFail(BABYLON2.Engine.KEEP);
engine.setStencilOperationDepthFail(BABYLON2.Engine.KEEP);
engine.setStencilMask(0);
engine.setStencilBuffer(true);
engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
if (this.outerGlow) {
effect.setFloat("offset", 0);
engine.setStencilFunction(BABYLON2.Engine.NOTEQUAL);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
}
if (this.innerGlow) {
effect.setFloat("offset", 1);
engine.setStencilFunction(BABYLON2.Engine.EQUAL);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
}
engine.setStencilFunction(previousStencilFunction);
engine.setStencilMask(previousStencilMask);
engine.setStencilBuffer(previousStencilBuffer);
engine.setStencilOperationPass(previousStencilOperationPass);
engine.setStencilOperationFail(previousStencilOperationFail);
engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
engine.setStencilFunctionReference(previousStencilReference);
};
HighlightLayer2.prototype.shouldRender = function() {
if (_super.prototype.shouldRender.call(this)) {
return this._meshes ? true : false;
}
return false;
};
HighlightLayer2.prototype._shouldRenderMesh = function(mesh2) {
if (this._excludedMeshes && this._excludedMeshes[mesh2.uniqueId]) {
return false;
}
if (!_super.prototype.hasMesh.call(this, mesh2)) {
return false;
}
return true;
};
HighlightLayer2.prototype._setEmissiveTextureAndColor = function(mesh2, subMesh, material) {
var highlightLayerMesh = this._meshes[mesh2.uniqueId];
if (highlightLayerMesh) {
this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1);
} else {
this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
}
if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
this._emissiveTextureAndColor.texture = material.emissiveTexture;
this._emissiveTextureAndColor.color.set(1, 1, 1, 1);
} else {
this._emissiveTextureAndColor.texture = null;
}
};
HighlightLayer2.prototype.addExcludedMesh = function(mesh2) {
if (!this._excludedMeshes) {
return;
}
var meshExcluded = this._excludedMeshes[mesh2.uniqueId];
if (!meshExcluded) {
this._excludedMeshes[mesh2.uniqueId] = {
mesh: mesh2,
beforeRender: mesh2.onBeforeRenderObservable.add(function(mesh3) {
mesh3.getEngine().setStencilBuffer(false);
}),
afterRender: mesh2.onAfterRenderObservable.add(function(mesh3) {
mesh3.getEngine().setStencilBuffer(true);
})
};
}
};
HighlightLayer2.prototype.removeExcludedMesh = function(mesh2) {
if (!this._excludedMeshes) {
return;
}
var meshExcluded = this._excludedMeshes[mesh2.uniqueId];
if (meshExcluded) {
if (meshExcluded.beforeRender) {
mesh2.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
}
if (meshExcluded.afterRender) {
mesh2.onAfterRenderObservable.remove(meshExcluded.afterRender);
}
}
this._excludedMeshes[mesh2.uniqueId] = null;
};
HighlightLayer2.prototype.hasMesh = function(mesh2) {
if (!this._meshes) {
return false;
}
if (!_super.prototype.hasMesh.call(this, mesh2)) {
return false;
}
return this._meshes[mesh2.uniqueId] !== void 0 && this._meshes[mesh2.uniqueId] !== null;
};
HighlightLayer2.prototype.addMesh = function(mesh2, color, glowEmissiveOnly) {
var _this = this;
if (glowEmissiveOnly === void 0) {
glowEmissiveOnly = false;
}
if (!this._meshes) {
return;
}
var meshHighlight = this._meshes[mesh2.uniqueId];
if (meshHighlight) {
meshHighlight.color = color;
} else {
this._meshes[mesh2.uniqueId] = {
mesh: mesh2,
color,
// Lambda required for capture due to Observable this context
observerHighlight: mesh2.onBeforeRenderObservable.add(function(mesh3) {
if (_this._excludedMeshes && _this._excludedMeshes[mesh3.uniqueId]) {
_this._defaultStencilReference(mesh3);
} else {
mesh3.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
}
}),
observerDefault: mesh2.onAfterRenderObservable.add(this._defaultStencilReference),
glowEmissiveOnly
};
mesh2.onDisposeObservable.add(function() {
_this._disposeMesh(mesh2);
});
}
this._shouldRender = true;
};
HighlightLayer2.prototype.removeMesh = function(mesh2) {
if (!this._meshes) {
return;
}
var meshHighlight = this._meshes[mesh2.uniqueId];
if (meshHighlight) {
if (meshHighlight.observerHighlight) {
mesh2.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
}
if (meshHighlight.observerDefault) {
mesh2.onAfterRenderObservable.remove(meshHighlight.observerDefault);
}
delete this._meshes[mesh2.uniqueId];
}
this._shouldRender = false;
for (var meshHighlightToCheck in this._meshes) {
if (this._meshes[meshHighlightToCheck]) {
this._shouldRender = true;
break;
}
}
};
HighlightLayer2.prototype._defaultStencilReference = function(mesh2) {
mesh2.getScene().getEngine().setStencilFunctionReference(HighlightLayer2.NormalMeshStencilReference);
};
HighlightLayer2.prototype._disposeMesh = function(mesh2) {
this.removeMesh(mesh2);
this.removeExcludedMesh(mesh2);
};
HighlightLayer2.prototype.dispose = function() {
if (this._meshes) {
for (var id in this._meshes) {
var meshHighlight = this._meshes[id];
if (meshHighlight && meshHighlight.mesh) {
if (meshHighlight.observerHighlight) {
meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
}
if (meshHighlight.observerDefault) {
meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
}
}
}
this._meshes = null;
}
if (this._excludedMeshes) {
for (var id in this._excludedMeshes) {
var meshHighlight = this._excludedMeshes[id];
if (meshHighlight) {
if (meshHighlight.beforeRender) {
meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
}
if (meshHighlight.afterRender) {
meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
}
}
}
this._excludedMeshes = null;
}
_super.prototype.dispose.call(this);
};
HighlightLayer2.prototype.getClassName = function() {
return "HighlightLayer";
};
HighlightLayer2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.HighlightLayer";
serializationObject.meshes = [];
if (this._meshes) {
for (var m in this._meshes) {
var mesh2 = this._meshes[m];
if (mesh2) {
serializationObject.meshes.push({
glowEmissiveOnly: mesh2.glowEmissiveOnly,
color: mesh2.color.asArray(),
meshId: mesh2.mesh.id
});
}
}
}
serializationObject.excludedMeshes = [];
if (this._excludedMeshes) {
for (var e2 in this._excludedMeshes) {
var excludedMesh = this._excludedMeshes[e2];
if (excludedMesh) {
serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
}
}
}
return serializationObject;
};
HighlightLayer2.Parse = function(parsedHightlightLayer, scene, rootUrl) {
var hl = BABYLON2.SerializationHelper.Parse(function() {
return new HighlightLayer2(parsedHightlightLayer.name, scene, parsedHightlightLayer.options);
}, parsedHightlightLayer, scene, rootUrl);
var index;
for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
var mesh2 = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
if (mesh2) {
hl.addExcludedMesh(mesh2);
}
}
for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
var highlightedMesh = parsedHightlightLayer.meshes[index];
var mesh2 = scene.getMeshByID(highlightedMesh.meshId);
if (mesh2) {
hl.addMesh(mesh2, BABYLON2.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
}
}
return hl;
};
HighlightLayer2.EffectName = "HighlightLayer";
HighlightLayer2.NeutralColor = new BABYLON2.Color4(0, 0, 0, 0);
HighlightLayer2.GlowingMeshStencilReference = 2;
HighlightLayer2.NormalMeshStencilReference = 1;
__decorate([
BABYLON2.serialize()
], HighlightLayer2.prototype, "innerGlow", void 0);
__decorate([
BABYLON2.serialize()
], HighlightLayer2.prototype, "outerGlow", void 0);
__decorate([
BABYLON2.serialize()
], HighlightLayer2.prototype, "blurHorizontalSize", null);
__decorate([
BABYLON2.serialize()
], HighlightLayer2.prototype, "blurVerticalSize", null);
__decorate([
BABYLON2.serialize("options")
], HighlightLayer2.prototype, "_options", void 0);
return HighlightLayer2;
}(BABYLON2.EffectLayer)
);
BABYLON2.HighlightLayer = HighlightLayer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.AbstractScene.prototype.getGlowLayerByName = function(name) {
for (var index = 0; index < this.effectLayers.length; index++) {
if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
return this.effectLayers[index];
}
}
return null;
};
var GlowLayer = (
/** @class */
function(_super) {
__extends(GlowLayer2, _super);
function GlowLayer2(name, scene, options) {
var _this = _super.call(this, name, scene) || this;
_this._intensity = 1;
_this._includedOnlyMeshes = [];
_this._excludedMeshes = [];
_this.neutralColor = new BABYLON2.Color4(0, 0, 0, 1);
_this._options = __assign({ mainTextureRatio: GlowLayer2.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: void 0, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
_this._init({
alphaBlendingMode: BABYLON2.Engine.ALPHA_ADD,
camera: _this._options.camera,
mainTextureFixedSize: _this._options.mainTextureFixedSize,
mainTextureRatio: _this._options.mainTextureRatio,
renderingGroupId: _this._options.renderingGroupId
});
return _this;
}
Object.defineProperty(GlowLayer2.prototype, "blurKernelSize", {
/**
* Gets the kernel size of the blur.
*/
get: function() {
return this._horizontalBlurPostprocess1.kernel;
},
/**
* Sets the kernel size of the blur.
*/
set: function(value) {
this._horizontalBlurPostprocess1.kernel = value;
this._verticalBlurPostprocess1.kernel = value;
this._horizontalBlurPostprocess2.kernel = value;
this._verticalBlurPostprocess2.kernel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(GlowLayer2.prototype, "intensity", {
/**
* Gets the glow intensity.
*/
get: function() {
return this._intensity;
},
/**
* Sets the glow intensity.
*/
set: function(value) {
this._intensity = value;
},
enumerable: true,
configurable: true
});
GlowLayer2.prototype.getEffectName = function() {
return GlowLayer2.EffectName;
};
GlowLayer2.prototype._createMergeEffect = function() {
return this._engine.createEffect("glowMapMerge", [BABYLON2.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
};
GlowLayer2.prototype._createTextureAndPostProcesses = function() {
var _this = this;
var blurTextureWidth = this._mainTextureDesiredSize.width;
var blurTextureHeight = this._mainTextureDesiredSize.height;
blurTextureWidth = this._engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
blurTextureHeight = this._engine.needPOTTextures ? BABYLON2.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
var textureType = 0;
if (this._engine.getCaps().textureHalfFloatRender) {
textureType = BABYLON2.Engine.TEXTURETYPE_HALF_FLOAT;
} else {
textureType = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
}
this._blurTexture1 = new BABYLON2.RenderTargetTexture("GlowLayerBlurRTT", {
width: blurTextureWidth,
height: blurTextureHeight
}, this._scene, false, true, textureType);
this._blurTexture1.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._blurTexture1.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._blurTexture1.updateSamplingMode(BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
this._blurTexture1.renderParticles = false;
this._blurTexture1.ignoreCameraViewport = true;
var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
this._blurTexture2 = new BABYLON2.RenderTargetTexture("GlowLayerBlurRTT2", {
width: blurTextureWidth2,
height: blurTextureHeight2
}, this._scene, false, true, textureType);
this._blurTexture2.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._blurTexture2.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
this._blurTexture2.updateSamplingMode(BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
this._blurTexture2.renderParticles = false;
this._blurTexture2.ignoreCameraViewport = true;
this._textures = [this._blurTexture1, this._blurTexture2];
this._horizontalBlurPostprocess1 = new BABYLON2.BlurPostProcess("GlowLayerHBP1", new BABYLON2.Vector2(1, 0), this._options.blurKernelSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess1.width = blurTextureWidth;
this._horizontalBlurPostprocess1.height = blurTextureHeight;
this._horizontalBlurPostprocess1.onApplyObservable.add(function(effect) {
effect.setTexture("textureSampler", _this._mainTexture);
});
this._verticalBlurPostprocess1 = new BABYLON2.BlurPostProcess("GlowLayerVBP1", new BABYLON2.Vector2(0, 1), this._options.blurKernelSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess2 = new BABYLON2.BlurPostProcess("GlowLayerHBP2", new BABYLON2.Vector2(1, 0), this._options.blurKernelSize / 2, {
width: blurTextureWidth2,
height: blurTextureHeight2
}, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess2.width = blurTextureWidth2;
this._horizontalBlurPostprocess2.height = blurTextureHeight2;
this._horizontalBlurPostprocess2.onApplyObservable.add(function(effect) {
effect.setTexture("textureSampler", _this._blurTexture1);
});
this._verticalBlurPostprocess2 = new BABYLON2.BlurPostProcess("GlowLayerVBP2", new BABYLON2.Vector2(0, 1), this._options.blurKernelSize / 2, {
width: blurTextureWidth2,
height: blurTextureHeight2
}, null, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
this._mainTexture.samples = this._options.mainTextureSamples;
this._mainTexture.onAfterUnbindObservable.add(function() {
var internalTexture = _this._blurTexture1.getInternalTexture();
if (internalTexture) {
_this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
internalTexture = _this._blurTexture2.getInternalTexture();
if (internalTexture) {
_this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
}
}
});
this._postProcesses.map(function(pp) {
pp.autoClear = false;
});
};
GlowLayer2.prototype.isReady = function(subMesh, useInstances) {
var material = subMesh.getMaterial();
var mesh2 = subMesh.getRenderingMesh();
if (!material || !mesh2) {
return false;
}
var emissiveTexture = material.emissiveTexture;
return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
};
GlowLayer2.prototype.needStencil = function() {
return false;
};
GlowLayer2.prototype._internalRender = function(effect) {
effect.setTexture("textureSampler", this._blurTexture1);
effect.setTexture("textureSampler2", this._blurTexture2);
effect.setFloat("offset", this._intensity);
var engine = this._engine;
var previousStencilBuffer = engine.getStencilBuffer();
engine.setStencilBuffer(false);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
engine.setStencilBuffer(previousStencilBuffer);
};
GlowLayer2.prototype._setEmissiveTextureAndColor = function(mesh2, subMesh, material) {
var textureLevel = 1;
if (this.customEmissiveTextureSelector) {
this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh2, subMesh, material);
} else {
if (material) {
this._emissiveTextureAndColor.texture = material.emissiveTexture;
if (this._emissiveTextureAndColor.texture) {
textureLevel = this._emissiveTextureAndColor.texture.level;
}
} else {
this._emissiveTextureAndColor.texture = null;
}
}
if (this.customEmissiveColorSelector) {
this.customEmissiveColorSelector(mesh2, subMesh, material, this._emissiveTextureAndColor.color);
} else {
if (material.emissiveColor) {
this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1);
} else {
this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
}
}
};
GlowLayer2.prototype._shouldRenderMesh = function(mesh2) {
return this.hasMesh(mesh2);
};
GlowLayer2.prototype.addExcludedMesh = function(mesh2) {
if (this._excludedMeshes.indexOf(mesh2.uniqueId) === -1) {
this._excludedMeshes.push(mesh2.uniqueId);
}
};
GlowLayer2.prototype.removeExcludedMesh = function(mesh2) {
var index = this._excludedMeshes.indexOf(mesh2.uniqueId);
if (index !== -1) {
this._excludedMeshes.splice(index, 1);
}
};
GlowLayer2.prototype.addIncludedOnlyMesh = function(mesh2) {
if (this._includedOnlyMeshes.indexOf(mesh2.uniqueId) === -1) {
this._includedOnlyMeshes.push(mesh2.uniqueId);
}
};
GlowLayer2.prototype.removeIncludedOnlyMesh = function(mesh2) {
var index = this._includedOnlyMeshes.indexOf(mesh2.uniqueId);
if (index !== -1) {
this._includedOnlyMeshes.splice(index, 1);
}
};
GlowLayer2.prototype.hasMesh = function(mesh2) {
if (!_super.prototype.hasMesh.call(this, mesh2)) {
return false;
}
if (this._includedOnlyMeshes.length) {
return this._includedOnlyMeshes.indexOf(mesh2.uniqueId) !== -1;
}
if (this._excludedMeshes.length) {
return this._excludedMeshes.indexOf(mesh2.uniqueId) === -1;
}
return true;
};
GlowLayer2.prototype._disposeMesh = function(mesh2) {
this.removeIncludedOnlyMesh(mesh2);
this.removeExcludedMesh(mesh2);
};
GlowLayer2.prototype.getClassName = function() {
return "GlowLayer";
};
GlowLayer2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.GlowLayer";
var index;
serializationObject.includedMeshes = [];
if (this._includedOnlyMeshes.length) {
for (index = 0; index < this._includedOnlyMeshes.length; index++) {
var mesh2 = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
if (mesh2) {
serializationObject.includedMeshes.push(mesh2.id);
}
}
}
serializationObject.excludedMeshes = [];
if (this._excludedMeshes.length) {
for (index = 0; index < this._excludedMeshes.length; index++) {
var mesh2 = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
if (mesh2) {
serializationObject.excludedMeshes.push(mesh2.id);
}
}
}
return serializationObject;
};
GlowLayer2.Parse = function(parsedGlowLayer, scene, rootUrl) {
var gl = BABYLON2.SerializationHelper.Parse(function() {
return new GlowLayer2(parsedGlowLayer.name, scene, parsedGlowLayer.options);
}, parsedGlowLayer, scene, rootUrl);
var index;
for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
var mesh2 = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
if (mesh2) {
gl.addExcludedMesh(mesh2);
}
}
for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
var mesh2 = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
if (mesh2) {
gl.addIncludedOnlyMesh(mesh2);
}
}
return gl;
};
GlowLayer2.EffectName = "GlowLayer";
GlowLayer2.DefaultBlurKernelSize = 32;
GlowLayer2.DefaultTextureRatio = 0.5;
__decorate([
BABYLON2.serialize()
], GlowLayer2.prototype, "blurKernelSize", null);
__decorate([
BABYLON2.serialize()
], GlowLayer2.prototype, "intensity", null);
__decorate([
BABYLON2.serialize("options")
], GlowLayer2.prototype, "_options", void 0);
return GlowLayer2;
}(BABYLON2.EffectLayer)
);
BABYLON2.GlowLayer = GlowLayer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var AssetTaskState;
(function(AssetTaskState2) {
AssetTaskState2[AssetTaskState2["INIT"] = 0] = "INIT";
AssetTaskState2[AssetTaskState2["RUNNING"] = 1] = "RUNNING";
AssetTaskState2[AssetTaskState2["DONE"] = 2] = "DONE";
AssetTaskState2[AssetTaskState2["ERROR"] = 3] = "ERROR";
})(AssetTaskState = BABYLON2.AssetTaskState || (BABYLON2.AssetTaskState = {}));
var AbstractAssetTask = (
/** @class */
function() {
function AbstractAssetTask2(name) {
this.name = name;
this._isCompleted = false;
this._taskState = AssetTaskState.INIT;
}
Object.defineProperty(AbstractAssetTask2.prototype, "isCompleted", {
/**
* Get if the task is completed
*/
get: function() {
return this._isCompleted;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractAssetTask2.prototype, "taskState", {
/**
* Gets the current state of the task
*/
get: function() {
return this._taskState;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbstractAssetTask2.prototype, "errorObject", {
/**
* Gets the current error object (if task is in error)
*/
get: function() {
return this._errorObject;
},
enumerable: true,
configurable: true
});
AbstractAssetTask2.prototype._setErrorObject = function(message, exception) {
if (this._errorObject) {
return;
}
this._errorObject = {
message,
exception
};
};
AbstractAssetTask2.prototype.run = function(scene, onSuccess, onError) {
var _this = this;
this._taskState = AssetTaskState.RUNNING;
this.runTask(scene, function() {
_this.onDoneCallback(onSuccess, onError);
}, function(msg, exception) {
_this.onErrorCallback(onError, msg, exception);
});
};
AbstractAssetTask2.prototype.runTask = function(scene, onSuccess, onError) {
throw new Error("runTask is not implemented");
};
AbstractAssetTask2.prototype.reset = function() {
this._taskState = AssetTaskState.INIT;
};
AbstractAssetTask2.prototype.onErrorCallback = function(onError, message, exception) {
this._taskState = AssetTaskState.ERROR;
this._errorObject = {
message,
exception
};
if (this.onError) {
this.onError(this, message, exception);
}
onError();
};
AbstractAssetTask2.prototype.onDoneCallback = function(onSuccess, onError) {
try {
this._taskState = AssetTaskState.DONE;
this._isCompleted = true;
if (this.onSuccess) {
this.onSuccess(this);
}
onSuccess();
} catch (e2) {
this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e2);
}
};
return AbstractAssetTask2;
}()
);
BABYLON2.AbstractAssetTask = AbstractAssetTask;
var AssetsProgressEvent = (
/** @class */
function() {
function AssetsProgressEvent2(remainingCount, totalCount, task) {
this.remainingCount = remainingCount;
this.totalCount = totalCount;
this.task = task;
}
return AssetsProgressEvent2;
}()
);
BABYLON2.AssetsProgressEvent = AssetsProgressEvent;
var MeshAssetTask = (
/** @class */
function(_super) {
__extends(MeshAssetTask2, _super);
function MeshAssetTask2(name, meshesNames, rootUrl, sceneFilename) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this.meshesNames = meshesNames;
_this.rootUrl = rootUrl;
_this.sceneFilename = sceneFilename;
return _this;
}
MeshAssetTask2.prototype.runTask = function(scene, onSuccess, onError) {
var _this = this;
BABYLON2.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function(meshes, particleSystems, skeletons) {
_this.loadedMeshes = meshes;
_this.loadedParticleSystems = particleSystems;
_this.loadedSkeletons = skeletons;
onSuccess();
}, null, function(scene2, message, exception) {
onError(message, exception);
});
};
return MeshAssetTask2;
}(AbstractAssetTask)
);
BABYLON2.MeshAssetTask = MeshAssetTask;
var TextFileAssetTask = (
/** @class */
function(_super) {
__extends(TextFileAssetTask2, _super);
function TextFileAssetTask2(name, url) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this.url = url;
return _this;
}
TextFileAssetTask2.prototype.runTask = function(scene, onSuccess, onError) {
var _this = this;
scene._loadFile(this.url, function(data2) {
_this.text = data2;
onSuccess();
}, void 0, false, false, function(request, exception) {
if (request) {
onError(request.status + " " + request.statusText, exception);
}
});
};
return TextFileAssetTask2;
}(AbstractAssetTask)
);
BABYLON2.TextFileAssetTask = TextFileAssetTask;
var BinaryFileAssetTask = (
/** @class */
function(_super) {
__extends(BinaryFileAssetTask2, _super);
function BinaryFileAssetTask2(name, url) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this.url = url;
return _this;
}
BinaryFileAssetTask2.prototype.runTask = function(scene, onSuccess, onError) {
var _this = this;
scene._loadFile(this.url, function(data2) {
_this.data = data2;
onSuccess();
}, void 0, true, true, function(request, exception) {
if (request) {
onError(request.status + " " + request.statusText, exception);
}
});
};
return BinaryFileAssetTask2;
}(AbstractAssetTask)
);
BABYLON2.BinaryFileAssetTask = BinaryFileAssetTask;
var ImageAssetTask = (
/** @class */
function(_super) {
__extends(ImageAssetTask2, _super);
function ImageAssetTask2(name, url) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this.url = url;
return _this;
}
ImageAssetTask2.prototype.runTask = function(scene, onSuccess, onError) {
var _this = this;
var img = new Image();
BABYLON2.Tools.SetCorsBehavior(this.url, img);
img.onload = function() {
_this.image = img;
onSuccess();
};
img.onerror = function(err) {
onError("Error loading image", err);
};
img.src = this.url;
};
return ImageAssetTask2;
}(AbstractAssetTask)
);
BABYLON2.ImageAssetTask = ImageAssetTask;
var TextureAssetTask = (
/** @class */
function(_super) {
__extends(TextureAssetTask2, _super);
function TextureAssetTask2(name, url, noMipmap, invertY, samplingMode) {
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
var _this = _super.call(this, name) || this;
_this.name = name;
_this.url = url;
_this.noMipmap = noMipmap;
_this.invertY = invertY;
_this.samplingMode = samplingMode;
return _this;
}
TextureAssetTask2.prototype.runTask = function(scene, onSuccess, onError) {
var onload = function() {
onSuccess();
};
var onerror = function(message, exception) {
onError(message, exception);
};
this.texture = new BABYLON2.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
};
return TextureAssetTask2;
}(AbstractAssetTask)
);
BABYLON2.TextureAssetTask = TextureAssetTask;
var CubeTextureAssetTask = (
/** @class */
function(_super) {
__extends(CubeTextureAssetTask2, _super);
function CubeTextureAssetTask2(name, url, extensions, noMipmap, files) {
var _this = _super.call(this, name) || this;
_this.name = name;
_this.url = url;
_this.extensions = extensions;
_this.noMipmap = noMipmap;
_this.files = files;
return _this;
}
CubeTextureAssetTask2.prototype.runTask = function(scene, onSuccess, onError) {
var onload = function() {
onSuccess();
};
var onerror = function(message, exception) {
onError(message, exception);
};
this.texture = new BABYLON2.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
};
return CubeTextureAssetTask2;
}(AbstractAssetTask)
);
BABYLON2.CubeTextureAssetTask = CubeTextureAssetTask;
var HDRCubeTextureAssetTask = (
/** @class */
function(_super) {
__extends(HDRCubeTextureAssetTask2, _super);
function HDRCubeTextureAssetTask2(name, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
if (noMipmap === void 0) {
noMipmap = false;
}
if (generateHarmonics === void 0) {
generateHarmonics = true;
}
if (gammaSpace === void 0) {
gammaSpace = false;
}
if (reserved === void 0) {
reserved = false;
}
var _this = _super.call(this, name) || this;
_this.name = name;
_this.url = url;
_this.size = size;
_this.noMipmap = noMipmap;
_this.generateHarmonics = generateHarmonics;
_this.gammaSpace = gammaSpace;
_this.reserved = reserved;
return _this;
}
HDRCubeTextureAssetTask2.prototype.run = function(scene, onSuccess, onError) {
var onload = function() {
onSuccess();
};
var onerror = function(message, exception) {
onError(message, exception);
};
this.texture = new BABYLON2.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
};
return HDRCubeTextureAssetTask2;
}(AbstractAssetTask)
);
BABYLON2.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
var AssetsManager = (
/** @class */
function() {
function AssetsManager2(scene) {
this._isLoading = false;
this._tasks = new Array();
this._waitingTasksCount = 0;
this._totalTasksCount = 0;
this.onTaskSuccessObservable = new BABYLON2.Observable();
this.onTaskErrorObservable = new BABYLON2.Observable();
this.onTasksDoneObservable = new BABYLON2.Observable();
this.onProgressObservable = new BABYLON2.Observable();
this.useDefaultLoadingScreen = true;
this._scene = scene;
}
AssetsManager2.prototype.addMeshTask = function(taskName, meshesNames, rootUrl, sceneFilename) {
var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
this._tasks.push(task);
return task;
};
AssetsManager2.prototype.addTextFileTask = function(taskName, url) {
var task = new TextFileAssetTask(taskName, url);
this._tasks.push(task);
return task;
};
AssetsManager2.prototype.addBinaryFileTask = function(taskName, url) {
var task = new BinaryFileAssetTask(taskName, url);
this._tasks.push(task);
return task;
};
AssetsManager2.prototype.addImageTask = function(taskName, url) {
var task = new ImageAssetTask(taskName, url);
this._tasks.push(task);
return task;
};
AssetsManager2.prototype.addTextureTask = function(taskName, url, noMipmap, invertY, samplingMode) {
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
this._tasks.push(task);
return task;
};
AssetsManager2.prototype.addCubeTextureTask = function(taskName, url, extensions, noMipmap, files) {
var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
this._tasks.push(task);
return task;
};
AssetsManager2.prototype.addHDRCubeTextureTask = function(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
if (noMipmap === void 0) {
noMipmap = false;
}
if (generateHarmonics === void 0) {
generateHarmonics = true;
}
if (gammaSpace === void 0) {
gammaSpace = false;
}
if (reserved === void 0) {
reserved = false;
}
var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
this._tasks.push(task);
return task;
};
AssetsManager2.prototype.removeTask = function(task) {
var index = this._tasks.indexOf(task);
if (index > -1) {
this._tasks.splice(index, 1);
}
};
AssetsManager2.prototype._decreaseWaitingTasksCount = function(task) {
this._waitingTasksCount--;
try {
if (this.onProgress) {
this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
}
this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
} catch (e2) {
BABYLON2.Tools.Error("Error running progress callbacks.");
console.log(e2);
}
if (this._waitingTasksCount === 0) {
try {
if (this.onFinish) {
this.onFinish(this._tasks);
}
var currentTasks = this._tasks.slice();
for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
var task = currentTasks_1[_i];
if (task.taskState === AssetTaskState.DONE) {
var index = this._tasks.indexOf(task);
if (index > -1) {
this._tasks.splice(index, 1);
}
}
}
this.onTasksDoneObservable.notifyObservers(this._tasks);
} catch (e2) {
BABYLON2.Tools.Error("Error running tasks-done callbacks.");
console.log(e2);
}
this._isLoading = false;
this._scene.getEngine().hideLoadingUI();
}
};
AssetsManager2.prototype._runTask = function(task) {
var _this = this;
var done = function() {
try {
if (_this.onTaskSuccess) {
_this.onTaskSuccess(task);
}
_this.onTaskSuccessObservable.notifyObservers(task);
_this._decreaseWaitingTasksCount(task);
} catch (e2) {
error("Error executing task success callbacks", e2);
}
};
var error = function(message, exception) {
task._setErrorObject(message, exception);
if (_this.onTaskError) {
_this.onTaskError(task);
}
_this.onTaskErrorObservable.notifyObservers(task);
_this._decreaseWaitingTasksCount(task);
};
task.run(this._scene, done, error);
};
AssetsManager2.prototype.reset = function() {
this._isLoading = false;
this._tasks = new Array();
return this;
};
AssetsManager2.prototype.load = function() {
if (this._isLoading) {
return this;
}
this._isLoading = true;
this._waitingTasksCount = this._tasks.length;
this._totalTasksCount = this._tasks.length;
if (this._waitingTasksCount === 0) {
this._isLoading = false;
if (this.onFinish) {
this.onFinish(this._tasks);
}
this.onTasksDoneObservable.notifyObservers(this._tasks);
return this;
}
if (this.useDefaultLoadingScreen) {
this._scene.getEngine().displayLoadingUI();
}
for (var index = 0; index < this._tasks.length; index++) {
var task = this._tasks[index];
if (task.taskState === AssetTaskState.INIT) {
this._runTask(task);
}
}
return this;
};
return AssetsManager2;
}()
);
BABYLON2.AssetsManager = AssetsManager;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var serializedGeometries = [];
var serializeGeometry = function(geometry, serializationGeometries) {
if (serializedGeometries[geometry.id]) {
return;
}
if (geometry.doNotSerialize) {
return;
}
if (geometry instanceof BABYLON2.BoxGeometry) {
serializationGeometries.boxes.push(geometry.serialize());
} else if (geometry instanceof BABYLON2.SphereGeometry) {
serializationGeometries.spheres.push(geometry.serialize());
} else if (geometry instanceof BABYLON2.CylinderGeometry) {
serializationGeometries.cylinders.push(geometry.serialize());
} else if (geometry instanceof BABYLON2.TorusGeometry) {
serializationGeometries.toruses.push(geometry.serialize());
} else if (geometry instanceof BABYLON2.GroundGeometry) {
serializationGeometries.grounds.push(geometry.serialize());
} else if (geometry instanceof BABYLON2.Plane) {
serializationGeometries.planes.push(geometry.serialize());
} else if (geometry instanceof BABYLON2.TorusKnotGeometry) {
serializationGeometries.torusKnots.push(geometry.serialize());
} else if (geometry instanceof BABYLON2._PrimitiveGeometry) {
throw new Error("Unknown primitive type");
} else {
serializationGeometries.vertexData.push(geometry.serializeVerticeData());
}
serializedGeometries[geometry.id] = true;
};
var serializeMesh = function(mesh2, serializationScene) {
var serializationObject = {};
var geometry = mesh2._geometry;
if (geometry) {
if (!mesh2.getScene().getGeometryByID(geometry.id)) {
serializeGeometry(geometry, serializationScene.geometries);
}
}
if (mesh2.serialize) {
mesh2.serialize(serializationObject);
}
return serializationObject;
};
var finalizeSingleMesh = function(mesh2, serializationObject) {
if (mesh2.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_LOADED || mesh2.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_NONE) {
if (mesh2.material) {
if (mesh2.material instanceof BABYLON2.MultiMaterial) {
serializationObject.multiMaterials = serializationObject.multiMaterials || [];
serializationObject.materials = serializationObject.materials || [];
if (!serializationObject.multiMaterials.some(function(mat) {
return mat.id === mesh2.material.id;
})) {
serializationObject.multiMaterials.push(mesh2.material.serialize());
var _loop_1 = function(submaterial2) {
if (submaterial2) {
if (!serializationObject.materials.some(function(mat) {
return mat.id === submaterial2.id;
})) {
serializationObject.materials.push(submaterial2.serialize());
}
}
};
for (var _i = 0, _a = mesh2.material.subMaterials; _i < _a.length; _i++) {
var submaterial = _a[_i];
_loop_1(submaterial);
}
}
} else {
serializationObject.materials = serializationObject.materials || [];
if (!serializationObject.materials.some(function(mat) {
return mat.id === mesh2.material.id;
})) {
serializationObject.materials.push(mesh2.material.serialize());
}
}
}
var geometry = mesh2._geometry;
if (geometry) {
if (!serializationObject.geometries) {
serializationObject.geometries = {};
serializationObject.geometries.boxes = [];
serializationObject.geometries.spheres = [];
serializationObject.geometries.cylinders = [];
serializationObject.geometries.toruses = [];
serializationObject.geometries.grounds = [];
serializationObject.geometries.planes = [];
serializationObject.geometries.torusKnots = [];
serializationObject.geometries.vertexData = [];
}
serializeGeometry(geometry, serializationObject.geometries);
}
if (mesh2.skeleton) {
serializationObject.skeletons = serializationObject.skeletons || [];
serializationObject.skeletons.push(mesh2.skeleton.serialize());
}
serializationObject.meshes = serializationObject.meshes || [];
serializationObject.meshes.push(serializeMesh(mesh2, serializationObject));
}
};
var SceneSerializer = (
/** @class */
function() {
function SceneSerializer2() {
}
SceneSerializer2.ClearCache = function() {
serializedGeometries = [];
};
SceneSerializer2.Serialize = function(scene) {
var serializationObject = {};
SceneSerializer2.ClearCache();
serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
serializationObject.autoClear = scene.autoClear;
serializationObject.clearColor = scene.clearColor.asArray();
serializationObject.ambientColor = scene.ambientColor.asArray();
serializationObject.gravity = scene.gravity.asArray();
serializationObject.collisionsEnabled = scene.collisionsEnabled;
serializationObject.workerCollisions = scene.workerCollisions;
if (scene.fogMode && scene.fogMode !== 0) {
serializationObject.fogMode = scene.fogMode;
serializationObject.fogColor = scene.fogColor.asArray();
serializationObject.fogStart = scene.fogStart;
serializationObject.fogEnd = scene.fogEnd;
serializationObject.fogDensity = scene.fogDensity;
}
if (scene.isPhysicsEnabled()) {
var physicEngine = scene.getPhysicsEngine();
if (physicEngine) {
serializationObject.physicsEnabled = true;
serializationObject.physicsGravity = physicEngine.gravity.asArray();
serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
}
}
if (scene.metadata) {
serializationObject.metadata = scene.metadata;
}
serializationObject.morphTargetManagers = [];
for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
var abstractMesh = _a[_i];
var manager = abstractMesh.morphTargetManager;
if (manager) {
serializationObject.morphTargetManagers.push(manager.serialize());
}
}
serializationObject.lights = [];
var index;
var light;
for (index = 0; index < scene.lights.length; index++) {
light = scene.lights[index];
if (!light.doNotSerialize) {
serializationObject.lights.push(light.serialize());
}
}
serializationObject.cameras = [];
for (index = 0; index < scene.cameras.length; index++) {
var camera2 = scene.cameras[index];
if (!camera2.doNotSerialize) {
serializationObject.cameras.push(camera2.serialize());
}
}
if (scene.activeCamera) {
serializationObject.activeCameraID = scene.activeCamera.id;
}
BABYLON2.Animation.AppendSerializedAnimations(scene, serializationObject);
serializationObject.materials = [];
serializationObject.multiMaterials = [];
var material;
for (index = 0; index < scene.materials.length; index++) {
material = scene.materials[index];
if (!material.doNotSerialize) {
serializationObject.materials.push(material.serialize());
}
}
serializationObject.multiMaterials = [];
for (index = 0; index < scene.multiMaterials.length; index++) {
var multiMaterial = scene.multiMaterials[index];
serializationObject.multiMaterials.push(multiMaterial.serialize());
}
if (scene.environmentTexture) {
serializationObject.environmentTexture = scene.environmentTexture.name;
}
serializationObject.skeletons = [];
for (index = 0; index < scene.skeletons.length; index++) {
var skeleton = scene.skeletons[index];
if (!skeleton.doNotSerialize) {
serializationObject.skeletons.push(skeleton.serialize());
}
}
serializationObject.transformNodes = [];
for (index = 0; index < scene.transformNodes.length; index++) {
serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
}
serializationObject.geometries = {};
serializationObject.geometries.boxes = [];
serializationObject.geometries.spheres = [];
serializationObject.geometries.cylinders = [];
serializationObject.geometries.toruses = [];
serializationObject.geometries.grounds = [];
serializationObject.geometries.planes = [];
serializationObject.geometries.torusKnots = [];
serializationObject.geometries.vertexData = [];
serializedGeometries = [];
var geometries = scene.getGeometries();
for (index = 0; index < geometries.length; index++) {
var geometry = geometries[index];
if (geometry.isReady()) {
serializeGeometry(geometry, serializationObject.geometries);
}
}
serializationObject.meshes = [];
for (index = 0; index < scene.meshes.length; index++) {
var abstractMesh = scene.meshes[index];
if (abstractMesh instanceof BABYLON2.Mesh) {
var mesh2 = abstractMesh;
if (!mesh2.doNotSerialize) {
if (mesh2.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_LOADED || mesh2.delayLoadState === BABYLON2.Engine.DELAYLOADSTATE_NONE) {
serializationObject.meshes.push(serializeMesh(mesh2, serializationObject));
}
}
}
}
serializationObject.particleSystems = [];
for (index = 0; index < scene.particleSystems.length; index++) {
serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
}
if (scene.actionManager) {
serializationObject.actions = scene.actionManager.serialize("scene");
}
for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
var component = _c[_b];
component.serialize(serializationObject);
}
return serializationObject;
};
SceneSerializer2.SerializeMesh = function(toSerialize, withParents, withChildren) {
if (withParents === void 0) {
withParents = false;
}
if (withChildren === void 0) {
withChildren = false;
}
var serializationObject = {};
SceneSerializer2.ClearCache();
toSerialize = toSerialize instanceof Array ? toSerialize : [toSerialize];
if (withParents || withChildren) {
for (var i2 = 0; i2 < toSerialize.length; ++i2) {
if (withChildren) {
toSerialize[i2].getDescendants().forEach(function(node) {
if (node instanceof BABYLON2.Mesh && toSerialize.indexOf(node) < 0) {
toSerialize.push(node);
}
});
}
if (withParents && toSerialize[i2].parent && toSerialize.indexOf(toSerialize[i2].parent) < 0) {
toSerialize.push(toSerialize[i2].parent);
}
}
}
toSerialize.forEach(function(mesh2) {
finalizeSingleMesh(mesh2, serializationObject);
});
return serializationObject;
};
return SceneSerializer2;
}()
);
BABYLON2.SceneSerializer = SceneSerializer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var ReflectionProbe = (
/** @class */
function() {
function ReflectionProbe2(name, size, scene, generateMipMaps, useFloat) {
if (generateMipMaps === void 0) {
generateMipMaps = true;
}
if (useFloat === void 0) {
useFloat = false;
}
var _this = this;
this.name = name;
this._viewMatrix = BABYLON2.Matrix.Identity();
this._target = BABYLON2.Vector3.Zero();
this._add = BABYLON2.Vector3.Zero();
this._invertYAxis = false;
this.position = BABYLON2.Vector3.Zero();
this._scene = scene;
if (!this._scene.reflectionProbes) {
this._scene.reflectionProbes = new Array();
}
this._scene.reflectionProbes.push(this);
this._renderTargetTexture = new BABYLON2.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON2.Engine.TEXTURETYPE_FLOAT : BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT, true);
this._renderTargetTexture.onBeforeRenderObservable.add(function(faceIndex) {
switch (faceIndex) {
case 0:
_this._add.copyFromFloats(1, 0, 0);
break;
case 1:
_this._add.copyFromFloats(-1, 0, 0);
break;
case 2:
_this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
break;
case 3:
_this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
break;
case 4:
_this._add.copyFromFloats(0, 0, 1);
break;
case 5:
_this._add.copyFromFloats(0, 0, -1);
break;
}
if (_this._attachedMesh) {
_this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
}
_this.position.addToRef(_this._add, _this._target);
BABYLON2.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON2.Vector3.Up(), _this._viewMatrix);
scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
scene._forcedViewPosition = _this.position;
});
this._renderTargetTexture.onAfterUnbindObservable.add(function() {
scene._forcedViewPosition = null;
scene.updateTransformMatrix(true);
});
if (scene.activeCamera) {
this._projectionMatrix = BABYLON2.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
}
}
Object.defineProperty(ReflectionProbe2.prototype, "samples", {
/** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
get: function() {
return this._renderTargetTexture.samples;
},
set: function(value) {
this._renderTargetTexture.samples = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ReflectionProbe2.prototype, "refreshRate", {
/** Gets or sets the refresh rate to use (on every frame by default) */
get: function() {
return this._renderTargetTexture.refreshRate;
},
set: function(value) {
this._renderTargetTexture.refreshRate = value;
},
enumerable: true,
configurable: true
});
ReflectionProbe2.prototype.getScene = function() {
return this._scene;
};
Object.defineProperty(ReflectionProbe2.prototype, "cubeTexture", {
/** Gets the internal CubeTexture used to render to */
get: function() {
return this._renderTargetTexture;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ReflectionProbe2.prototype, "renderList", {
/** Gets the list of meshes to render */
get: function() {
return this._renderTargetTexture.renderList;
},
enumerable: true,
configurable: true
});
ReflectionProbe2.prototype.attachToMesh = function(mesh2) {
this._attachedMesh = mesh2;
};
ReflectionProbe2.prototype.setRenderingAutoClearDepthStencil = function(renderingGroupId, autoClearDepthStencil) {
this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
};
ReflectionProbe2.prototype.dispose = function() {
var index = this._scene.reflectionProbes.indexOf(this);
if (index !== -1) {
this._scene.reflectionProbes.splice(index, 1);
}
if (this._renderTargetTexture) {
this._renderTargetTexture.dispose();
this._renderTargetTexture = null;
}
};
return ReflectionProbe2;
}()
);
BABYLON2.ReflectionProbe = ReflectionProbe;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var LayerSceneComponent = (
/** @class */
function() {
function LayerSceneComponent2(scene) {
this.name = BABYLON2.SceneComponentConstants.NAME_LAYER;
this.scene = scene;
this._engine = scene.getEngine();
scene.layers = new Array();
}
LayerSceneComponent2.prototype.register = function() {
this.scene._beforeCameraDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
this.scene._afterCameraDrawStage.registerStep(BABYLON2.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
};
LayerSceneComponent2.prototype.rebuild = function() {
var layers = this.scene.layers;
for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
var layer = layers_1[_i];
layer._rebuild();
}
};
LayerSceneComponent2.prototype.dispose = function() {
var layers = this.scene.layers;
while (layers.length) {
layers[0].dispose();
}
};
LayerSceneComponent2.prototype._draw = function(camera2, isBackground) {
var layers = this.scene.layers;
if (layers.length) {
this._engine.setDepthBuffer(false);
var cameraLayerMask = camera2.layerMask;
for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
var layer = layers_2[_i];
if (layer.isBackground === isBackground && (layer.layerMask & cameraLayerMask) !== 0) {
layer.render();
}
}
this._engine.setDepthBuffer(true);
}
};
LayerSceneComponent2.prototype._drawBackground = function(camera2) {
this._draw(camera2, true);
};
LayerSceneComponent2.prototype._drawForeground = function(camera2) {
this._draw(camera2, false);
};
return LayerSceneComponent2;
}()
);
BABYLON2.LayerSceneComponent = LayerSceneComponent;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var Layer = (
/** @class */
function() {
function Layer2(name, imgUrl, scene, isBackground, color) {
this.name = name;
this.scale = new BABYLON2.Vector2(1, 1);
this.offset = new BABYLON2.Vector2(0, 0);
this.alphaBlendingMode = BABYLON2.Engine.ALPHA_COMBINE;
this.layerMask = 268435455;
this._vertexBuffers = {};
this.onDisposeObservable = new BABYLON2.Observable();
this.onBeforeRenderObservable = new BABYLON2.Observable();
this.onAfterRenderObservable = new BABYLON2.Observable();
this.texture = imgUrl ? new BABYLON2.Texture(imgUrl, scene, true) : null;
this.isBackground = isBackground === void 0 ? true : isBackground;
this.color = color === void 0 ? new BABYLON2.Color4(1, 1, 1, 1) : color;
this._scene = scene || BABYLON2.Engine.LastCreatedScene;
var layerComponent = this._scene._getComponent(BABYLON2.SceneComponentConstants.NAME_LAYER);
if (!layerComponent) {
layerComponent = new BABYLON2.LayerSceneComponent(this._scene);
this._scene._addComponent(layerComponent);
}
this._scene.layers.push(this);
var engine = this._scene.getEngine();
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
var vertexBuffer = new BABYLON2.VertexBuffer(engine, vertices, BABYLON2.VertexBuffer.PositionKind, false, false, 2);
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = vertexBuffer;
this._createIndexBuffer();
this._effect = engine.createEffect("layer", [BABYLON2.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
this._alphaTestEffect = engine.createEffect("layer", [BABYLON2.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
}
Object.defineProperty(Layer2.prototype, "onDispose", {
/**
* Back compatibility with callback before the onDisposeObservable existed.
* The set callback will be triggered when the layer has been disposed.
*/
set: function(callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Layer2.prototype, "onBeforeRender", {
/**
* Back compatibility with callback before the onBeforeRenderObservable existed.
* The set callback will be triggered just before rendering the layer.
*/
set: function(callback) {
if (this._onBeforeRenderObserver) {
this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
}
this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Layer2.prototype, "onAfterRender", {
/**
* Back compatibility with callback before the onAfterRenderObservable existed.
* The set callback will be triggered just after rendering the layer.
*/
set: function(callback) {
if (this._onAfterRenderObserver) {
this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
}
this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
},
enumerable: true,
configurable: true
});
Layer2.prototype._createIndexBuffer = function() {
var engine = this._scene.getEngine();
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = engine.createIndexBuffer(indices);
};
Layer2.prototype._rebuild = function() {
var vb = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vb) {
vb._rebuild();
}
this._createIndexBuffer();
};
Layer2.prototype.render = function() {
var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
return;
}
var engine = this._scene.getEngine();
this.onBeforeRenderObservable.notifyObservers(this);
engine.enableEffect(currentEffect);
engine.setState(false);
currentEffect.setTexture("textureSampler", this.texture);
currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
currentEffect.setVector2("offset", this.offset);
currentEffect.setVector2("scale", this.scale);
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
if (!this.alphaTest) {
engine.setAlphaMode(this.alphaBlendingMode);
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
engine.setAlphaMode(BABYLON2.Engine.ALPHA_DISABLE);
} else {
engine.drawElementsType(BABYLON2.Material.TriangleFillMode, 0, 6);
}
this.onAfterRenderObservable.notifyObservers(this);
};
Layer2.prototype.dispose = function() {
var vertexBuffer = this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[BABYLON2.VertexBuffer.PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
if (this.texture) {
this.texture.dispose();
this.texture = null;
}
var index = this._scene.layers.indexOf(this);
this._scene.layers.splice(index, 1);
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onAfterRenderObservable.clear();
this.onBeforeRenderObservable.clear();
};
return Layer2;
}()
);
BABYLON2.Layer = Layer;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var TextureTools = (
/** @class */
function() {
function TextureTools2() {
}
TextureTools2.CreateResizedCopy = function(texture, width, height, useBilinearMode) {
if (useBilinearMode === void 0) {
useBilinearMode = true;
}
var scene = texture.getScene();
var engine = scene.getEngine();
var rtt = new BABYLON2.RenderTargetTexture("resized" + texture.name, { width, height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
rtt.wrapU = texture.wrapU;
rtt.wrapV = texture.wrapV;
rtt.uOffset = texture.uOffset;
rtt.vOffset = texture.vOffset;
rtt.uScale = texture.uScale;
rtt.vScale = texture.vScale;
rtt.uAng = texture.uAng;
rtt.vAng = texture.vAng;
rtt.wAng = texture.wAng;
rtt.coordinatesIndex = texture.coordinatesIndex;
rtt.level = texture.level;
rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
rtt._texture.isReady = false;
texture.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
texture.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
var passPostProcess = new BABYLON2.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON2.Texture.BILINEAR_SAMPLINGMODE : BABYLON2.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT);
passPostProcess.getEffect().executeWhenCompiled(function() {
passPostProcess.onApply = function(effect) {
effect.setTexture("textureSampler", texture);
};
var internalTexture = rtt.getInternalTexture();
if (internalTexture) {
scene.postProcessManager.directRender([passPostProcess], internalTexture);
engine.unBindFramebuffer(internalTexture);
rtt.disposeFramebufferObjects();
passPostProcess.dispose();
internalTexture.isReady = true;
}
});
return rtt;
};
TextureTools2.GetEnvironmentBRDFTexture = function(scene) {
if (!scene._environmentBRDFTexture) {
var texture = BABYLON2.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON2.Texture.BILINEAR_SAMPLINGMODE);
texture.wrapU = BABYLON2.Texture.CLAMP_ADDRESSMODE;
texture.wrapV = BABYLON2.Texture.CLAMP_ADDRESSMODE;
scene._environmentBRDFTexture = texture;
}
return scene._environmentBRDFTexture;
};
TextureTools2._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
return TextureTools2;
}()
);
BABYLON2.TextureTools = TextureTools;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var FramingBehavior = (
/** @class */
function() {
function FramingBehavior2() {
this._mode = FramingBehavior2.FitFrustumSidesMode;
this._radiusScale = 1;
this._positionScale = 0.5;
this._defaultElevation = 0.3;
this._elevationReturnTime = 1500;
this._elevationReturnWaitTime = 1e3;
this._zoomStopsAnimation = false;
this._framingTime = 1500;
this.autoCorrectCameraLimitsAndSensibility = true;
this._isPointerDown = false;
this._lastInteractionTime = -Infinity;
this._animatables = new Array();
this._betaIsAnimating = false;
}
Object.defineProperty(FramingBehavior2.prototype, "name", {
/**
* Gets the name of the behavior.
*/
get: function() {
return "Framing";
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "mode", {
/**
* Gets current mode used by the behavior.
*/
get: function() {
return this._mode;
},
/**
* Sets the current mode used by the behavior
*/
set: function(mode) {
this._mode = mode;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "radiusScale", {
/**
* Gets the scale applied to the radius
*/
get: function() {
return this._radiusScale;
},
/**
* Sets the scale applied to the radius (1 by default)
*/
set: function(radius) {
this._radiusScale = radius;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "positionScale", {
/**
* Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
*/
get: function() {
return this._positionScale;
},
/**
* Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
*/
set: function(scale) {
this._positionScale = scale;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "defaultElevation", {
/**
* Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
* behaviour is triggered, in radians.
*/
get: function() {
return this._defaultElevation;
},
/**
* Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
* behaviour is triggered, in radians.
*/
set: function(elevation) {
this._defaultElevation = elevation;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "elevationReturnTime", {
/**
* Gets the time (in milliseconds) taken to return to the default beta position.
* Negative value indicates camera should not return to default.
*/
get: function() {
return this._elevationReturnTime;
},
/**
* Sets the time (in milliseconds) taken to return to the default beta position.
* Negative value indicates camera should not return to default.
*/
set: function(speed) {
this._elevationReturnTime = speed;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "elevationReturnWaitTime", {
/**
* Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
*/
get: function() {
return this._elevationReturnWaitTime;
},
/**
* Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
*/
set: function(time) {
this._elevationReturnWaitTime = time;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "zoomStopsAnimation", {
/**
* Gets the flag that indicates if user zooming should stop animation.
*/
get: function() {
return this._zoomStopsAnimation;
},
/**
* Sets the flag that indicates if user zooming should stop animation.
*/
set: function(flag) {
this._zoomStopsAnimation = flag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FramingBehavior2.prototype, "framingTime", {
/**
* Gets the transition time when framing the mesh, in milliseconds
*/
get: function() {
return this._framingTime;
},
/**
* Sets the transition time when framing the mesh, in milliseconds
*/
set: function(time) {
this._framingTime = time;
},
enumerable: true,
configurable: true
});
FramingBehavior2.prototype.init = function() {
};
FramingBehavior2.prototype.attach = function(camera2) {
var _this = this;
this._attachedCamera = camera2;
var scene = this._attachedCamera.getScene();
FramingBehavior2.EasingFunction.setEasingMode(FramingBehavior2.EasingMode);
this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function(pointerInfoPre) {
if (pointerInfoPre.type === BABYLON2.PointerEventTypes.POINTERDOWN) {
_this._isPointerDown = true;
return;
}
if (pointerInfoPre.type === BABYLON2.PointerEventTypes.POINTERUP) {
_this._isPointerDown = false;
}
});
this._onMeshTargetChangedObserver = camera2.onMeshTargetChangedObservable.add(function(mesh2) {
if (mesh2) {
_this.zoomOnMesh(mesh2);
}
});
this._onAfterCheckInputsObserver = camera2.onAfterCheckInputsObservable.add(function() {
_this._applyUserInteraction();
_this._maintainCameraAboveGround();
});
};
FramingBehavior2.prototype.detach = function() {
if (!this._attachedCamera) {
return;
}
var scene = this._attachedCamera.getScene();
if (this._onPrePointerObservableObserver) {
scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
}
if (this._onAfterCheckInputsObserver) {
this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
}
if (this._onMeshTargetChangedObserver) {
this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
}
this._attachedCamera = null;
};
FramingBehavior2.prototype.zoomOnMesh = function(mesh2, focusOnOriginXZ, onAnimationEnd) {
if (focusOnOriginXZ === void 0) {
focusOnOriginXZ = false;
}
if (onAnimationEnd === void 0) {
onAnimationEnd = null;
}
mesh2.computeWorldMatrix(true);
var boundingBox = mesh2.getBoundingInfo().boundingBox;
this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
};
FramingBehavior2.prototype.zoomOnMeshHierarchy = function(mesh2, focusOnOriginXZ, onAnimationEnd) {
if (focusOnOriginXZ === void 0) {
focusOnOriginXZ = false;
}
if (onAnimationEnd === void 0) {
onAnimationEnd = null;
}
mesh2.computeWorldMatrix(true);
var boundingBox = mesh2.getHierarchyBoundingVectors(true);
this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
};
FramingBehavior2.prototype.zoomOnMeshesHierarchy = function(meshes, focusOnOriginXZ, onAnimationEnd) {
if (focusOnOriginXZ === void 0) {
focusOnOriginXZ = false;
}
if (onAnimationEnd === void 0) {
onAnimationEnd = null;
}
var min = new BABYLON2.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
var max = new BABYLON2.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
for (var i2 = 0; i2 < meshes.length; i2++) {
var boundingInfo = meshes[i2].getHierarchyBoundingVectors(true);
BABYLON2.Tools.CheckExtends(boundingInfo.min, min, max);
BABYLON2.Tools.CheckExtends(boundingInfo.max, min, max);
}
this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
};
FramingBehavior2.prototype.zoomOnBoundingInfo = function(minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
var _this = this;
if (focusOnOriginXZ === void 0) {
focusOnOriginXZ = false;
}
if (onAnimationEnd === void 0) {
onAnimationEnd = null;
}
var zoomTarget;
if (!this._attachedCamera) {
return;
}
var bottom = minimumWorld.y;
var top = maximumWorld.y;
var zoomTargetY = bottom + (top - bottom) * this._positionScale;
var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
if (focusOnOriginXZ) {
zoomTarget = new BABYLON2.Vector3(0, zoomTargetY, 0);
} else {
var centerWorld = minimumWorld.add(radiusWorld);
zoomTarget = new BABYLON2.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
}
if (!this._vectorTransition) {
this._vectorTransition = BABYLON2.Animation.CreateAnimation("target", BABYLON2.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior2.EasingFunction);
}
this._betaIsAnimating = true;
var animatable = BABYLON2.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
if (animatable) {
this._animatables.push(animatable);
}
var radius = 0;
if (this._mode === FramingBehavior2.FitFrustumSidesMode) {
var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
if (this.autoCorrectCameraLimitsAndSensibility) {
this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
}
radius = position;
} else if (this._mode === FramingBehavior2.IgnoreBoundsSizeMode) {
radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
}
}
if (this.autoCorrectCameraLimitsAndSensibility) {
var extend = maximumWorld.subtract(minimumWorld).length();
this._attachedCamera.panningSensibility = 5e3 / extend;
this._attachedCamera.wheelPrecision = 100 / radius;
}
if (!this._radiusTransition) {
this._radiusTransition = BABYLON2.Animation.CreateAnimation("radius", BABYLON2.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior2.EasingFunction);
}
animatable = BABYLON2.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function() {
_this.stopAllAnimations();
if (onAnimationEnd) {
onAnimationEnd();
}
if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
_this._attachedCamera.storeState();
}
});
if (animatable) {
this._animatables.push(animatable);
}
};
FramingBehavior2.prototype._calculateLowerRadiusFromModelBoundingSphere = function(minimumWorld, maximumWorld) {
var size = maximumWorld.subtract(minimumWorld);
var boxVectorGlobalDiagonal = size.length();
var frustumSlope = this._getFrustumSlope();
var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
var radius = radiusWithoutFraming * this._radiusScale;
var distanceForHorizontalFrustum = radius * Math.sqrt(1 + 1 / (frustumSlope.x * frustumSlope.x));
var distanceForVerticalFrustum = radius * Math.sqrt(1 + 1 / (frustumSlope.y * frustumSlope.y));
var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
var camera2 = this._attachedCamera;
if (!camera2) {
return 0;
}
if (camera2.lowerRadiusLimit && this._mode === FramingBehavior2.IgnoreBoundsSizeMode) {
distance = distance < camera2.lowerRadiusLimit ? camera2.lowerRadiusLimit : distance;
}
if (camera2.upperRadiusLimit) {
distance = distance > camera2.upperRadiusLimit ? camera2.upperRadiusLimit : distance;
}
return distance;
};
FramingBehavior2.prototype._maintainCameraAboveGround = function() {
var _this = this;
if (this._elevationReturnTime < 0) {
return;
}
var timeSinceInteraction = BABYLON2.Tools.Now - this._lastInteractionTime;
var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
var limitBeta = Math.PI * 0.5;
if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
this._betaIsAnimating = true;
this.stopAllAnimations();
if (!this._betaTransition) {
this._betaTransition = BABYLON2.Animation.CreateAnimation("beta", BABYLON2.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior2.EasingFunction);
}
var animatabe = BABYLON2.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function() {
_this._clearAnimationLocks();
_this.stopAllAnimations();
});
if (animatabe) {
this._animatables.push(animatabe);
}
}
};
FramingBehavior2.prototype._getFrustumSlope = function() {
var camera2 = this._attachedCamera;
if (!camera2) {
return BABYLON2.Vector2.Zero();
}
var engine = camera2.getScene().getEngine();
var aspectRatio = engine.getAspectRatio(camera2);
var frustumSlopeY = Math.tan(camera2.fov / 2);
var frustumSlopeX = frustumSlopeY * aspectRatio;
return new BABYLON2.Vector2(frustumSlopeX, frustumSlopeY);
};
FramingBehavior2.prototype._clearAnimationLocks = function() {
this._betaIsAnimating = false;
};
FramingBehavior2.prototype._applyUserInteraction = function() {
if (this.isUserIsMoving) {
this._lastInteractionTime = BABYLON2.Tools.Now;
this.stopAllAnimations();
this._clearAnimationLocks();
}
};
FramingBehavior2.prototype.stopAllAnimations = function() {
if (this._attachedCamera) {
this._attachedCamera.animations = [];
}
while (this._animatables.length) {
if (this._animatables[0]) {
this._animatables[0].onAnimationEnd = null;
this._animatables[0].stop();
}
this._animatables.shift();
}
};
Object.defineProperty(FramingBehavior2.prototype, "isUserIsMoving", {
/**
* Gets a value indicating if the user is moving the camera
*/
get: function() {
if (!this._attachedCamera) {
return false;
}
return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown;
},
enumerable: true,
configurable: true
});
FramingBehavior2.EasingFunction = new BABYLON2.ExponentialEase();
FramingBehavior2.EasingMode = BABYLON2.EasingFunction.EASINGMODE_EASEINOUT;
FramingBehavior2.IgnoreBoundsSizeMode = 0;
FramingBehavior2.FitFrustumSidesMode = 1;
return FramingBehavior2;
}()
);
BABYLON2.FramingBehavior = FramingBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BouncingBehavior = (
/** @class */
function() {
function BouncingBehavior2() {
this.transitionDuration = 450;
this.lowerRadiusTransitionRange = 2;
this.upperRadiusTransitionRange = -2;
this._autoTransitionRange = false;
this._radiusIsAnimating = false;
this._radiusBounceTransition = null;
this._animatables = new Array();
}
Object.defineProperty(BouncingBehavior2.prototype, "name", {
/**
* Gets the name of the behavior.
*/
get: function() {
return "Bouncing";
},
enumerable: true,
configurable: true
});
Object.defineProperty(BouncingBehavior2.prototype, "autoTransitionRange", {
/**
* Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
*/
get: function() {
return this._autoTransitionRange;
},
/**
* Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
* Transition ranges will be set to 5% of the bounding box diagonal in world space
*/
set: function(value) {
var _this = this;
if (this._autoTransitionRange === value) {
return;
}
this._autoTransitionRange = value;
var camera2 = this._attachedCamera;
if (!camera2) {
return;
}
if (value) {
this._onMeshTargetChangedObserver = camera2.onMeshTargetChangedObservable.add(function(mesh2) {
if (!mesh2) {
return;
}
mesh2.computeWorldMatrix(true);
var diagonal = mesh2.getBoundingInfo().diagonalLength;
_this.lowerRadiusTransitionRange = diagonal * 0.05;
_this.upperRadiusTransitionRange = diagonal * 0.05;
});
} else if (this._onMeshTargetChangedObserver) {
camera2.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
}
},
enumerable: true,
configurable: true
});
BouncingBehavior2.prototype.init = function() {
};
BouncingBehavior2.prototype.attach = function(camera2) {
var _this = this;
this._attachedCamera = camera2;
this._onAfterCheckInputsObserver = camera2.onAfterCheckInputsObservable.add(function() {
if (!_this._attachedCamera) {
return;
}
if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
_this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
}
if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
_this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
}
});
};
BouncingBehavior2.prototype.detach = function() {
if (!this._attachedCamera) {
return;
}
if (this._onAfterCheckInputsObserver) {
this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
}
if (this._onMeshTargetChangedObserver) {
this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
}
this._attachedCamera = null;
};
BouncingBehavior2.prototype._isRadiusAtLimit = function(radiusLimit) {
if (!this._attachedCamera) {
return false;
}
if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
return true;
}
return false;
};
BouncingBehavior2.prototype._applyBoundRadiusAnimation = function(radiusDelta) {
var _this = this;
if (!this._attachedCamera) {
return;
}
if (!this._radiusBounceTransition) {
BouncingBehavior2.EasingFunction.setEasingMode(BouncingBehavior2.EasingMode);
this._radiusBounceTransition = BABYLON2.Animation.CreateAnimation("radius", BABYLON2.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior2.EasingFunction);
}
this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
this._attachedCamera.wheelPrecision = Infinity;
this._attachedCamera.inertialRadiusOffset = 0;
this.stopAllAnimations();
this._radiusIsAnimating = true;
var animatable = BABYLON2.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function() {
return _this._clearAnimationLocks();
});
if (animatable) {
this._animatables.push(animatable);
}
};
BouncingBehavior2.prototype._clearAnimationLocks = function() {
this._radiusIsAnimating = false;
if (this._attachedCamera) {
this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
}
};
BouncingBehavior2.prototype.stopAllAnimations = function() {
if (this._attachedCamera) {
this._attachedCamera.animations = [];
}
while (this._animatables.length) {
this._animatables[0].onAnimationEnd = null;
this._animatables[0].stop();
this._animatables.shift();
}
};
BouncingBehavior2.EasingFunction = new BABYLON2.BackEase(0.3);
BouncingBehavior2.EasingMode = BABYLON2.EasingFunction.EASINGMODE_EASEOUT;
return BouncingBehavior2;
}()
);
BABYLON2.BouncingBehavior = BouncingBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var AutoRotationBehavior = (
/** @class */
function() {
function AutoRotationBehavior2() {
this._zoomStopsAnimation = false;
this._idleRotationSpeed = 0.05;
this._idleRotationWaitTime = 2e3;
this._idleRotationSpinupTime = 2e3;
this._isPointerDown = false;
this._lastFrameTime = null;
this._lastInteractionTime = -Infinity;
this._cameraRotationSpeed = 0;
this._lastFrameRadius = 0;
}
Object.defineProperty(AutoRotationBehavior2.prototype, "name", {
/**
* Gets the name of the behavior.
*/
get: function() {
return "AutoRotation";
},
enumerable: true,
configurable: true
});
Object.defineProperty(AutoRotationBehavior2.prototype, "zoomStopsAnimation", {
/**
* Gets the flag that indicates if user zooming should stop animation.
*/
get: function() {
return this._zoomStopsAnimation;
},
/**
* Sets the flag that indicates if user zooming should stop animation.
*/
set: function(flag) {
this._zoomStopsAnimation = flag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AutoRotationBehavior2.prototype, "idleRotationSpeed", {
/**
* Gets the default speed at which the camera rotates around the model.
*/
get: function() {
return this._idleRotationSpeed;
},
/**
* Sets the default speed at which the camera rotates around the model.
*/
set: function(speed) {
this._idleRotationSpeed = speed;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AutoRotationBehavior2.prototype, "idleRotationWaitTime", {
/**
* Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
*/
get: function() {
return this._idleRotationWaitTime;
},
/**
* Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
*/
set: function(time) {
this._idleRotationWaitTime = time;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AutoRotationBehavior2.prototype, "idleRotationSpinupTime", {
/**
* Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
*/
get: function() {
return this._idleRotationSpinupTime;
},
/**
* Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
*/
set: function(time) {
this._idleRotationSpinupTime = time;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AutoRotationBehavior2.prototype, "rotationInProgress", {
/**
* Gets a value indicating if the camera is currently rotating because of this behavior
*/
get: function() {
return Math.abs(this._cameraRotationSpeed) > 0;
},
enumerable: true,
configurable: true
});
AutoRotationBehavior2.prototype.init = function() {
};
AutoRotationBehavior2.prototype.attach = function(camera2) {
var _this = this;
this._attachedCamera = camera2;
var scene = this._attachedCamera.getScene();
this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function(pointerInfoPre) {
if (pointerInfoPre.type === BABYLON2.PointerEventTypes.POINTERDOWN) {
_this._isPointerDown = true;
return;
}
if (pointerInfoPre.type === BABYLON2.PointerEventTypes.POINTERUP) {
_this._isPointerDown = false;
}
});
this._onAfterCheckInputsObserver = camera2.onAfterCheckInputsObservable.add(function() {
var now2 = BABYLON2.Tools.Now;
var dt = 0;
if (_this._lastFrameTime != null) {
dt = now2 - _this._lastFrameTime;
}
_this._lastFrameTime = now2;
_this._applyUserInteraction();
var timeToRotation = now2 - _this._lastInteractionTime - _this._idleRotationWaitTime;
var scale = Math.max(Math.min(timeToRotation / _this._idleRotationSpinupTime, 1), 0);
_this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
if (_this._attachedCamera) {
_this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1e3);
}
});
};
AutoRotationBehavior2.prototype.detach = function() {
if (!this._attachedCamera) {
return;
}
var scene = this._attachedCamera.getScene();
if (this._onPrePointerObservableObserver) {
scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
}
this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
this._attachedCamera = null;
};
AutoRotationBehavior2.prototype._userIsZooming = function() {
if (!this._attachedCamera) {
return false;
}
return this._attachedCamera.inertialRadiusOffset !== 0;
};
AutoRotationBehavior2.prototype._shouldAnimationStopForInteraction = function() {
if (!this._attachedCamera) {
return false;
}
var zoomHasHitLimit = false;
if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
zoomHasHitLimit = true;
}
this._lastFrameRadius = this._attachedCamera.radius;
return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
};
AutoRotationBehavior2.prototype._applyUserInteraction = function() {
if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
this._lastInteractionTime = BABYLON2.Tools.Now;
}
};
AutoRotationBehavior2.prototype._userIsMoving = function() {
if (!this._attachedCamera) {
return false;
}
return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown;
};
return AutoRotationBehavior2;
}()
);
BABYLON2.AutoRotationBehavior = AutoRotationBehavior;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var NullEngineOptions = (
/** @class */
function() {
function NullEngineOptions2() {
this.renderWidth = 512;
this.renderHeight = 256;
this.textureSize = 512;
this.deterministicLockstep = false;
this.lockstepMaxSteps = 4;
}
return NullEngineOptions2;
}()
);
BABYLON2.NullEngineOptions = NullEngineOptions;
var NullEngine = (
/** @class */
function(_super) {
__extends(NullEngine2, _super);
function NullEngine2(options) {
if (options === void 0) {
options = new NullEngineOptions();
}
var _this = _super.call(this, null) || this;
if (options.deterministicLockstep === void 0) {
options.deterministicLockstep = false;
}
if (options.lockstepMaxSteps === void 0) {
options.lockstepMaxSteps = 4;
}
_this._options = options;
_this._caps = new BABYLON2.EngineCapabilities();
_this._caps.maxTexturesImageUnits = 16;
_this._caps.maxVertexTextureImageUnits = 16;
_this._caps.maxTextureSize = 512;
_this._caps.maxCubemapTextureSize = 512;
_this._caps.maxRenderTextureSize = 512;
_this._caps.maxVertexAttribs = 16;
_this._caps.maxVaryingVectors = 16;
_this._caps.maxFragmentUniformVectors = 16;
_this._caps.maxVertexUniformVectors = 16;
_this._caps.standardDerivatives = false;
_this._caps.astc = null;
_this._caps.s3tc = null;
_this._caps.pvrtc = null;
_this._caps.etc1 = null;
_this._caps.etc2 = null;
_this._caps.textureAnisotropicFilterExtension = null;
_this._caps.maxAnisotropy = 0;
_this._caps.uintIndices = false;
_this._caps.fragmentDepthSupported = false;
_this._caps.highPrecisionShaderSupported = true;
_this._caps.colorBufferFloat = false;
_this._caps.textureFloat = false;
_this._caps.textureFloatLinearFiltering = false;
_this._caps.textureFloatRender = false;
_this._caps.textureHalfFloat = false;
_this._caps.textureHalfFloatLinearFiltering = false;
_this._caps.textureHalfFloatRender = false;
_this._caps.textureLOD = false;
_this._caps.drawBuffersExtension = false;
_this._caps.depthTextureExtension = false;
_this._caps.vertexArrayObject = false;
_this._caps.instancedArrays = false;
BABYLON2.Tools.Log("Babylon.js null engine (v" + BABYLON2.Engine.Version + ") launched");
if (typeof URL === "undefined") {
URL = {
createObjectURL: function() {
},
revokeObjectURL: function() {
}
};
}
if (typeof Blob === "undefined") {
Blob = function() {
};
}
return _this;
}
NullEngine2.prototype.isDeterministicLockStep = function() {
return this._options.deterministicLockstep;
};
NullEngine2.prototype.getLockstepMaxSteps = function() {
return this._options.lockstepMaxSteps;
};
NullEngine2.prototype.getHardwareScalingLevel = function() {
return 1;
};
NullEngine2.prototype.createVertexBuffer = function(vertices) {
return {
capacity: 0,
references: 1,
is32Bits: false
};
};
NullEngine2.prototype.createIndexBuffer = function(indices) {
return {
capacity: 0,
references: 1,
is32Bits: false
};
};
NullEngine2.prototype.clear = function(color, backBuffer, depth, stencil) {
if (stencil === void 0) {
stencil = false;
}
};
NullEngine2.prototype.getRenderWidth = function(useScreen) {
if (useScreen === void 0) {
useScreen = false;
}
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.width;
}
return this._options.renderWidth;
};
NullEngine2.prototype.getRenderHeight = function(useScreen) {
if (useScreen === void 0) {
useScreen = false;
}
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.height;
}
return this._options.renderHeight;
};
NullEngine2.prototype.setViewport = function(viewport, requiredWidth, requiredHeight) {
this._cachedViewport = viewport;
};
NullEngine2.prototype.createShaderProgram = function(vertexCode, fragmentCode, defines, context) {
return {
transformFeedback: null,
__SPECTOR_rebuildProgram: null
};
};
NullEngine2.prototype.getUniforms = function(shaderProgram, uniformsNames) {
return [];
};
NullEngine2.prototype.getAttributes = function(shaderProgram, attributesNames) {
return [];
};
NullEngine2.prototype.bindSamplers = function(effect) {
this._currentEffect = null;
};
NullEngine2.prototype.enableEffect = function(effect) {
this._currentEffect = effect;
if (effect.onBind) {
effect.onBind(effect);
}
if (effect._onBindObservable) {
effect._onBindObservable.notifyObservers(effect);
}
};
NullEngine2.prototype.setState = function(culling, zOffset, force, reverseSide) {
if (zOffset === void 0) {
zOffset = 0;
}
if (reverseSide === void 0) {
reverseSide = false;
}
};
NullEngine2.prototype.setIntArray = function(uniform, array) {
};
NullEngine2.prototype.setIntArray2 = function(uniform, array) {
};
NullEngine2.prototype.setIntArray3 = function(uniform, array) {
};
NullEngine2.prototype.setIntArray4 = function(uniform, array) {
};
NullEngine2.prototype.setFloatArray = function(uniform, array) {
};
NullEngine2.prototype.setFloatArray2 = function(uniform, array) {
};
NullEngine2.prototype.setFloatArray3 = function(uniform, array) {
};
NullEngine2.prototype.setFloatArray4 = function(uniform, array) {
};
NullEngine2.prototype.setArray = function(uniform, array) {
};
NullEngine2.prototype.setArray2 = function(uniform, array) {
};
NullEngine2.prototype.setArray3 = function(uniform, array) {
};
NullEngine2.prototype.setArray4 = function(uniform, array) {
};
NullEngine2.prototype.setMatrices = function(uniform, matrices) {
};
NullEngine2.prototype.setMatrix = function(uniform, matrix) {
};
NullEngine2.prototype.setMatrix3x3 = function(uniform, matrix) {
};
NullEngine2.prototype.setMatrix2x2 = function(uniform, matrix) {
};
NullEngine2.prototype.setFloat = function(uniform, value) {
};
NullEngine2.prototype.setFloat2 = function(uniform, x, y) {
};
NullEngine2.prototype.setFloat3 = function(uniform, x, y, z) {
};
NullEngine2.prototype.setBool = function(uniform, bool) {
};
NullEngine2.prototype.setFloat4 = function(uniform, x, y, z, w) {
};
NullEngine2.prototype.setColor3 = function(uniform, color3) {
};
NullEngine2.prototype.setColor4 = function(uniform, color3, alpha) {
};
NullEngine2.prototype.setAlphaMode = function(mode, noDepthWriteChange) {
if (noDepthWriteChange === void 0) {
noDepthWriteChange = false;
}
if (this._alphaMode === mode) {
return;
}
this._alphaState.alphaBlend = mode !== BABYLON2.Engine.ALPHA_DISABLE;
if (!noDepthWriteChange) {
this.setDepthWrite(mode === BABYLON2.Engine.ALPHA_DISABLE);
}
this._alphaMode = mode;
};
NullEngine2.prototype.bindBuffers = function(vertexBuffers, indexBuffer, effect) {
};
NullEngine2.prototype.wipeCaches = function(bruteForce) {
if (this.preventCacheWipeBetweenFrames) {
return;
}
this.resetTextureCache();
this._currentEffect = null;
if (bruteForce) {
this._currentProgram = null;
this._stencilState.reset();
this._depthCullingState.reset();
this._alphaState.reset();
}
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._cachedEffectForVertexBuffers = null;
};
NullEngine2.prototype.draw = function(useTriangles, indexStart, indexCount, instancesCount) {
};
NullEngine2.prototype.drawElementsType = function(fillMode, indexStart, indexCount, instancesCount) {
};
NullEngine2.prototype.drawArraysType = function(fillMode, verticesStart, verticesCount, instancesCount) {
};
NullEngine2.prototype._createTexture = function() {
return {};
};
NullEngine2.prototype._releaseTexture = function(texture) {
};
NullEngine2.prototype.createTexture = function(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
if (samplingMode === void 0) {
samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
if (onLoad === void 0) {
onLoad = null;
}
if (onError === void 0) {
onError = null;
}
if (buffer === void 0) {
buffer = null;
}
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_URL);
var url = String(urlArg);
texture.url = url;
texture.generateMipMaps = !noMipmap;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
texture.baseWidth = this._options.textureSize;
texture.baseHeight = this._options.textureSize;
texture.width = this._options.textureSize;
texture.height = this._options.textureSize;
if (format) {
texture.format = format;
}
texture.isReady = true;
if (onLoad) {
onLoad();
}
this._internalTexturesCache.push(texture);
return texture;
};
NullEngine2.prototype.createRenderTargetTexture = function(size, options) {
var fullOptions = new BABYLON2.RenderTargetCreationOptions();
if (options !== void 0 && typeof options === "object") {
fullOptions.generateMipMaps = options.generateMipMaps;
fullOptions.generateDepthBuffer = options.generateDepthBuffer === void 0 ? true : options.generateDepthBuffer;
fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
fullOptions.type = options.type === void 0 ? BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
fullOptions.samplingMode = options.samplingMode === void 0 ? BABYLON2.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
} else {
fullOptions.generateMipMaps = options;
fullOptions.generateDepthBuffer = true;
fullOptions.generateStencilBuffer = false;
fullOptions.type = BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT;
fullOptions.samplingMode = BABYLON2.Texture.TRILINEAR_SAMPLINGMODE;
}
var texture = new BABYLON2.InternalTexture(this, BABYLON2.InternalTexture.DATASOURCE_RENDERTARGET);
var width = size.width || size;
var height = size.height || size;
texture._depthStencilBuffer = {};
texture._framebuffer = {};
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
this._internalTexturesCache.push(texture);
return texture;
};
NullEngine2.prototype.updateTextureSamplingMode = function(samplingMode, texture) {
texture.samplingMode = samplingMode;
};
NullEngine2.prototype.bindFramebuffer = function(texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
}
this._currentRenderTarget = texture;
this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
if (this._cachedViewport && !forceFullscreenViewport) {
this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
}
};
NullEngine2.prototype.unBindFramebuffer = function(texture, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) {
disableGenerateMipMaps = false;
}
this._currentRenderTarget = null;
if (onBeforeUnbind) {
if (texture._MSAAFramebuffer) {
this._currentFramebuffer = texture._framebuffer;
}
onBeforeUnbind();
}
this._currentFramebuffer = null;
};
NullEngine2.prototype.createDynamicVertexBuffer = function(vertices) {
var vbo = {
capacity: 1,
references: 1,
is32Bits: false
};
return vbo;
};
NullEngine2.prototype.updateDynamicTexture = function(texture, canvas2, invertY, premulAlpha, format) {
if (premulAlpha === void 0) {
premulAlpha = false;
}
};
NullEngine2.prototype.getError = function() {
return 0;
};
NullEngine2.prototype._getUnpackAlignement = function() {
return 1;
};
NullEngine2.prototype._unpackFlipY = function(value) {
};
NullEngine2.prototype.updateDynamicIndexBuffer = function(indexBuffer, indices, offset) {
if (offset === void 0) {
offset = 0;
}
};
NullEngine2.prototype.updateDynamicVertexBuffer = function(vertexBuffer, vertices, byteOffset, byteLength) {
};
NullEngine2.prototype._bindTextureDirectly = function(target, texture) {
if (this._boundTexturesCache[this._activeChannel] !== texture) {
this._boundTexturesCache[this._activeChannel] = texture;
return true;
}
return false;
};
NullEngine2.prototype._bindTexture = function(channel, texture) {
if (channel < 0) {
return;
}
this._bindTextureDirectly(0, texture);
};
NullEngine2.prototype._releaseBuffer = function(buffer) {
buffer.references--;
if (buffer.references === 0) {
return true;
}
return false;
};
NullEngine2.prototype.releaseEffects = function() {
};
NullEngine2.prototype.displayLoadingUI = function() {
};
NullEngine2.prototype.hideLoadingUI = function() {
};
NullEngine2.prototype._uploadCompressedDataToTextureDirectly = function(texture, internalFormat, width, height, data2, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
};
NullEngine2.prototype._uploadDataToTextureDirectly = function(texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
};
NullEngine2.prototype._uploadArrayBufferViewToTexture = function(texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
};
NullEngine2.prototype._uploadImageToTexture = function(texture, image, faceIndex, lod) {
if (faceIndex === void 0) {
faceIndex = 0;
}
if (lod === void 0) {
lod = 0;
}
};
return NullEngine2;
}(BABYLON2.Engine)
);
BABYLON2.NullEngine = NullEngine;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var EngineInstrumentation = (
/** @class */
function() {
function EngineInstrumentation2(engine) {
this.engine = engine;
this._captureGPUFrameTime = false;
this._gpuFrameTime = new BABYLON2.PerfCounter();
this._captureShaderCompilationTime = false;
this._shaderCompilationTime = new BABYLON2.PerfCounter();
this._onBeginFrameObserver = null;
this._onEndFrameObserver = null;
this._onBeforeShaderCompilationObserver = null;
this._onAfterShaderCompilationObserver = null;
}
Object.defineProperty(EngineInstrumentation2.prototype, "gpuFrameTimeCounter", {
// Properties
/**
* Gets the perf counter used for GPU frame time
*/
get: function() {
return this._gpuFrameTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EngineInstrumentation2.prototype, "captureGPUFrameTime", {
/**
* Gets the GPU frame time capture status
*/
get: function() {
return this._captureGPUFrameTime;
},
/**
* Enable or disable the GPU frame time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureGPUFrameTime) {
return;
}
this._captureGPUFrameTime = value;
if (value) {
this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function() {
if (!_this._gpuFrameTimeToken) {
_this._gpuFrameTimeToken = _this.engine.startTimeQuery();
}
});
this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function() {
if (!_this._gpuFrameTimeToken) {
return;
}
var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
if (time > -1) {
_this._gpuFrameTimeToken = null;
_this._gpuFrameTime.fetchNewFrame();
_this._gpuFrameTime.addCount(time, true);
}
});
} else {
this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
this._onBeginFrameObserver = null;
this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
this._onEndFrameObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(EngineInstrumentation2.prototype, "shaderCompilationTimeCounter", {
/**
* Gets the perf counter used for shader compilation time
*/
get: function() {
return this._shaderCompilationTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EngineInstrumentation2.prototype, "captureShaderCompilationTime", {
/**
* Gets the shader compilation time capture status
*/
get: function() {
return this._captureShaderCompilationTime;
},
/**
* Enable or disable the shader compilation time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureShaderCompilationTime) {
return;
}
this._captureShaderCompilationTime = value;
if (value) {
this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function() {
_this._shaderCompilationTime.fetchNewFrame();
_this._shaderCompilationTime.beginMonitoring();
});
this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function() {
_this._shaderCompilationTime.endMonitoring();
});
} else {
this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
this._onBeforeShaderCompilationObserver = null;
this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
this._onAfterShaderCompilationObserver = null;
}
},
enumerable: true,
configurable: true
});
EngineInstrumentation2.prototype.dispose = function() {
this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
this._onBeginFrameObserver = null;
this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
this._onEndFrameObserver = null;
this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
this._onBeforeShaderCompilationObserver = null;
this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
this._onAfterShaderCompilationObserver = null;
this.engine = null;
};
return EngineInstrumentation2;
}()
);
BABYLON2.EngineInstrumentation = EngineInstrumentation;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var SceneInstrumentation = (
/** @class */
function() {
function SceneInstrumentation2(scene) {
var _this = this;
this.scene = scene;
this._captureActiveMeshesEvaluationTime = false;
this._activeMeshesEvaluationTime = new BABYLON2.PerfCounter();
this._captureRenderTargetsRenderTime = false;
this._renderTargetsRenderTime = new BABYLON2.PerfCounter();
this._captureFrameTime = false;
this._frameTime = new BABYLON2.PerfCounter();
this._captureRenderTime = false;
this._renderTime = new BABYLON2.PerfCounter();
this._captureInterFrameTime = false;
this._interFrameTime = new BABYLON2.PerfCounter();
this._captureParticlesRenderTime = false;
this._particlesRenderTime = new BABYLON2.PerfCounter();
this._captureSpritesRenderTime = false;
this._spritesRenderTime = new BABYLON2.PerfCounter();
this._capturePhysicsTime = false;
this._physicsTime = new BABYLON2.PerfCounter();
this._captureAnimationsTime = false;
this._animationsTime = new BABYLON2.PerfCounter();
this._captureCameraRenderTime = false;
this._cameraRenderTime = new BABYLON2.PerfCounter();
this._onBeforeActiveMeshesEvaluationObserver = null;
this._onAfterActiveMeshesEvaluationObserver = null;
this._onBeforeRenderTargetsRenderObserver = null;
this._onAfterRenderTargetsRenderObserver = null;
this._onAfterRenderObserver = null;
this._onBeforeDrawPhaseObserver = null;
this._onAfterDrawPhaseObserver = null;
this._onBeforeAnimationsObserver = null;
this._onBeforeParticlesRenderingObserver = null;
this._onAfterParticlesRenderingObserver = null;
this._onBeforeSpritesRenderingObserver = null;
this._onAfterSpritesRenderingObserver = null;
this._onBeforePhysicsObserver = null;
this._onAfterPhysicsObserver = null;
this._onAfterAnimationsObserver = null;
this._onBeforeCameraRenderObserver = null;
this._onAfterCameraRenderObserver = null;
this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function() {
if (_this._captureActiveMeshesEvaluationTime) {
_this._activeMeshesEvaluationTime.fetchNewFrame();
}
if (_this._captureRenderTargetsRenderTime) {
_this._renderTargetsRenderTime.fetchNewFrame();
}
if (_this._captureFrameTime) {
BABYLON2.Tools.StartPerformanceCounter("Scene rendering");
_this._frameTime.beginMonitoring();
}
if (_this._captureInterFrameTime) {
_this._interFrameTime.endMonitoring();
}
if (_this._captureParticlesRenderTime) {
_this._particlesRenderTime.fetchNewFrame();
}
if (_this._captureSpritesRenderTime) {
_this._spritesRenderTime.fetchNewFrame();
}
if (_this._captureAnimationsTime) {
_this._animationsTime.beginMonitoring();
}
_this.scene.getEngine()._drawCalls.fetchNewFrame();
_this.scene.getEngine()._textureCollisions.fetchNewFrame();
});
this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function() {
if (_this._captureFrameTime) {
BABYLON2.Tools.EndPerformanceCounter("Scene rendering");
_this._frameTime.endMonitoring();
}
if (_this._captureRenderTime) {
_this._renderTime.endMonitoring(false);
}
if (_this._captureInterFrameTime) {
_this._interFrameTime.beginMonitoring();
}
});
}
Object.defineProperty(SceneInstrumentation2.prototype, "activeMeshesEvaluationTimeCounter", {
// Properties
/**
* Gets the perf counter used for active meshes evaluation time
*/
get: function() {
return this._activeMeshesEvaluationTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureActiveMeshesEvaluationTime", {
/**
* Gets the active meshes evaluation time capture status
*/
get: function() {
return this._captureActiveMeshesEvaluationTime;
},
/**
* Enable or disable the active meshes evaluation time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureActiveMeshesEvaluationTime) {
return;
}
this._captureActiveMeshesEvaluationTime = value;
if (value) {
this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function() {
BABYLON2.Tools.StartPerformanceCounter("Active meshes evaluation");
_this._activeMeshesEvaluationTime.beginMonitoring();
});
this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function() {
BABYLON2.Tools.EndPerformanceCounter("Active meshes evaluation");
_this._activeMeshesEvaluationTime.endMonitoring();
});
} else {
this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
this._onBeforeActiveMeshesEvaluationObserver = null;
this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
this._onAfterActiveMeshesEvaluationObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "renderTargetsRenderTimeCounter", {
/**
* Gets the perf counter used for render targets render time
*/
get: function() {
return this._renderTargetsRenderTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureRenderTargetsRenderTime", {
/**
* Gets the render targets render time capture status
*/
get: function() {
return this._captureRenderTargetsRenderTime;
},
/**
* Enable or disable the render targets render time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureRenderTargetsRenderTime) {
return;
}
this._captureRenderTargetsRenderTime = value;
if (value) {
this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function() {
BABYLON2.Tools.StartPerformanceCounter("Render targets rendering");
_this._renderTargetsRenderTime.beginMonitoring();
});
this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function() {
BABYLON2.Tools.EndPerformanceCounter("Render targets rendering");
_this._renderTargetsRenderTime.endMonitoring(false);
});
} else {
this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
this._onBeforeRenderTargetsRenderObserver = null;
this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
this._onAfterRenderTargetsRenderObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "particlesRenderTimeCounter", {
/**
* Gets the perf counter used for particles render time
*/
get: function() {
return this._particlesRenderTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureParticlesRenderTime", {
/**
* Gets the particles render time capture status
*/
get: function() {
return this._captureParticlesRenderTime;
},
/**
* Enable or disable the particles render time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureParticlesRenderTime) {
return;
}
this._captureParticlesRenderTime = value;
if (value) {
this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function() {
BABYLON2.Tools.StartPerformanceCounter("Particles");
_this._particlesRenderTime.beginMonitoring();
});
this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function() {
BABYLON2.Tools.EndPerformanceCounter("Particles");
_this._particlesRenderTime.endMonitoring(false);
});
} else {
this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
this._onBeforeParticlesRenderingObserver = null;
this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
this._onAfterParticlesRenderingObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "spritesRenderTimeCounter", {
/**
* Gets the perf counter used for sprites render time
*/
get: function() {
return this._spritesRenderTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureSpritesRenderTime", {
/**
* Gets the sprites render time capture status
*/
get: function() {
return this._captureSpritesRenderTime;
},
/**
* Enable or disable the sprites render time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureSpritesRenderTime) {
return;
}
this._captureSpritesRenderTime = value;
if (!this.scene.spriteManagers) {
return;
}
if (value) {
this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function() {
BABYLON2.Tools.StartPerformanceCounter("Sprites");
_this._spritesRenderTime.beginMonitoring();
});
this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function() {
BABYLON2.Tools.EndPerformanceCounter("Sprites");
_this._spritesRenderTime.endMonitoring(false);
});
} else {
this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
this._onBeforeSpritesRenderingObserver = null;
this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
this._onAfterSpritesRenderingObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "physicsTimeCounter", {
/**
* Gets the perf counter used for physics time
*/
get: function() {
return this._physicsTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "capturePhysicsTime", {
/**
* Gets the physics time capture status
*/
get: function() {
return this._capturePhysicsTime;
},
/**
* Enable or disable the physics time capture
*/
set: function(value) {
var _this = this;
if (value === this._capturePhysicsTime) {
return;
}
if (!this.scene.onBeforePhysicsObservable) {
return;
}
this._capturePhysicsTime = value;
if (value) {
this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function() {
BABYLON2.Tools.StartPerformanceCounter("Physics");
_this._physicsTime.beginMonitoring();
});
this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function() {
BABYLON2.Tools.EndPerformanceCounter("Physics");
_this._physicsTime.endMonitoring();
});
} else {
this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
this._onBeforePhysicsObserver = null;
this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
this._onAfterPhysicsObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "animationsTimeCounter", {
/**
* Gets the perf counter used for animations time
*/
get: function() {
return this._animationsTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureAnimationsTime", {
/**
* Gets the animations time capture status
*/
get: function() {
return this._captureAnimationsTime;
},
/**
* Enable or disable the animations time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureAnimationsTime) {
return;
}
this._captureAnimationsTime = value;
if (value) {
this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function() {
_this._animationsTime.endMonitoring();
});
} else {
this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
this._onAfterAnimationsObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "frameTimeCounter", {
/**
* Gets the perf counter used for frame time capture
*/
get: function() {
return this._frameTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureFrameTime", {
/**
* Gets the frame time capture status
*/
get: function() {
return this._captureFrameTime;
},
/**
* Enable or disable the frame time capture
*/
set: function(value) {
this._captureFrameTime = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "interFrameTimeCounter", {
/**
* Gets the perf counter used for inter-frames time capture
*/
get: function() {
return this._interFrameTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureInterFrameTime", {
/**
* Gets the inter-frames time capture status
*/
get: function() {
return this._captureInterFrameTime;
},
/**
* Enable or disable the inter-frames time capture
*/
set: function(value) {
this._captureInterFrameTime = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "renderTimeCounter", {
/**
* Gets the perf counter used for render time capture
*/
get: function() {
return this._renderTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureRenderTime", {
/**
* Gets the render time capture status
*/
get: function() {
return this._captureRenderTime;
},
/**
* Enable or disable the render time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureRenderTime) {
return;
}
this._captureRenderTime = value;
if (value) {
this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function() {
_this._renderTime.beginMonitoring();
BABYLON2.Tools.StartPerformanceCounter("Main render");
});
this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function() {
_this._renderTime.endMonitoring(false);
BABYLON2.Tools.EndPerformanceCounter("Main render");
});
} else {
this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
this._onBeforeDrawPhaseObserver = null;
this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
this._onAfterDrawPhaseObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "cameraRenderTimeCounter", {
/**
* Gets the perf counter used for camera render time capture
*/
get: function() {
return this._cameraRenderTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "captureCameraRenderTime", {
/**
* Gets the camera render time capture status
*/
get: function() {
return this._captureCameraRenderTime;
},
/**
* Enable or disable the camera render time capture
*/
set: function(value) {
var _this = this;
if (value === this._captureCameraRenderTime) {
return;
}
this._captureCameraRenderTime = value;
if (value) {
this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function(camera2) {
_this._cameraRenderTime.beginMonitoring();
BABYLON2.Tools.StartPerformanceCounter("Rendering camera " + camera2.name);
});
this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function(camera2) {
_this._cameraRenderTime.endMonitoring(false);
BABYLON2.Tools.EndPerformanceCounter("Rendering camera " + camera2.name);
});
} else {
this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
this._onBeforeCameraRenderObserver = null;
this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
this._onAfterCameraRenderObserver = null;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "drawCallsCounter", {
/**
* Gets the perf counter used for draw calls
*/
get: function() {
return this.scene.getEngine()._drawCalls;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SceneInstrumentation2.prototype, "textureCollisionsCounter", {
/**
* Gets the perf counter used for texture collisions
*/
get: function() {
return this.scene.getEngine()._textureCollisions;
},
enumerable: true,
configurable: true
});
SceneInstrumentation2.prototype.dispose = function() {
this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
this._onAfterRenderObserver = null;
this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
this._onBeforeActiveMeshesEvaluationObserver = null;
this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
this._onAfterActiveMeshesEvaluationObserver = null;
this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
this._onBeforeRenderTargetsRenderObserver = null;
this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
this._onAfterRenderTargetsRenderObserver = null;
this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
this._onBeforeAnimationsObserver = null;
this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
this._onBeforeParticlesRenderingObserver = null;
this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
this._onAfterParticlesRenderingObserver = null;
if (this._onBeforeSpritesRenderingObserver) {
this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
this._onBeforeSpritesRenderingObserver = null;
}
if (this._onAfterSpritesRenderingObserver) {
this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
this._onAfterSpritesRenderingObserver = null;
}
this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
this._onBeforeDrawPhaseObserver = null;
this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
this._onAfterDrawPhaseObserver = null;
if (this._onBeforePhysicsObserver) {
this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
this._onBeforePhysicsObserver = null;
}
if (this._onAfterPhysicsObserver) {
this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
this._onAfterPhysicsObserver = null;
}
this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
this._onAfterAnimationsObserver = null;
this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
this._onBeforeCameraRenderObserver = null;
this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
this._onAfterCameraRenderObserver = null;
this.scene = null;
};
return SceneInstrumentation2;
}()
);
BABYLON2.SceneInstrumentation = SceneInstrumentation;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _TimeToken = (
/** @class */
function() {
function _TimeToken2() {
this._timeElapsedQueryEnded = false;
}
return _TimeToken2;
}()
);
BABYLON2._TimeToken = _TimeToken;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var BackgroundMaterialDefines = (
/** @class */
function(_super) {
__extends(BackgroundMaterialDefines2, _super);
function BackgroundMaterialDefines2() {
var _this = _super.call(this) || this;
_this.DIFFUSE = false;
_this.DIFFUSEDIRECTUV = 0;
_this.GAMMADIFFUSE = false;
_this.DIFFUSEHASALPHA = false;
_this.OPACITYFRESNEL = false;
_this.REFLECTIONBLUR = false;
_this.REFLECTIONFRESNEL = false;
_this.REFLECTIONFALLOFF = false;
_this.TEXTURELODSUPPORT = false;
_this.PREMULTIPLYALPHA = false;
_this.USERGBCOLOR = false;
_this.USEHIGHLIGHTANDSHADOWCOLORS = false;
_this.NOISE = false;
_this.REFLECTIONBGR = false;
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.TONEMAPPING_ACES = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.EXPOSURE = false;
_this.REFLECTION = false;
_this.REFLECTIONMAP_3D = false;
_this.REFLECTIONMAP_SPHERICAL = false;
_this.REFLECTIONMAP_PLANAR = false;
_this.REFLECTIONMAP_CUBIC = false;
_this.REFLECTIONMAP_PROJECTION = false;
_this.REFLECTIONMAP_SKYBOX = false;
_this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
_this.REFLECTIONMAP_EXPLICIT = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
_this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
_this.INVERTCUBICMAP = false;
_this.REFLECTIONMAP_OPPOSITEZ = false;
_this.LODINREFLECTIONALPHA = false;
_this.GAMMAREFLECTION = false;
_this.RGBDREFLECTION = false;
_this.EQUIRECTANGULAR_RELFECTION_FOV = false;
_this.MAINUV1 = false;
_this.MAINUV2 = false;
_this.UV1 = false;
_this.UV2 = false;
_this.CLIPPLANE = false;
_this.CLIPPLANE2 = false;
_this.CLIPPLANE3 = false;
_this.CLIPPLANE4 = false;
_this.POINTSIZE = false;
_this.FOG = false;
_this.NORMAL = false;
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.INSTANCES = false;
_this.SHADOWFLOAT = false;
_this.rebuild();
return _this;
}
return BackgroundMaterialDefines2;
}(BABYLON2.MaterialDefines)
);
var BackgroundMaterial = (
/** @class */
function(_super) {
__extends(BackgroundMaterial2, _super);
function BackgroundMaterial2(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this.primaryColor = BABYLON2.Color3.White();
_this._primaryColorShadowLevel = 0;
_this._primaryColorHighlightLevel = 0;
_this.reflectionTexture = null;
_this.reflectionBlur = 0;
_this.diffuseTexture = null;
_this._shadowLights = null;
_this.shadowLights = null;
_this.shadowLevel = 0;
_this.sceneCenter = BABYLON2.Vector3.Zero();
_this.opacityFresnel = true;
_this.reflectionFresnel = false;
_this.reflectionFalloffDistance = 0;
_this.reflectionAmount = 1;
_this.reflectionReflectance0 = 0.05;
_this.reflectionReflectance90 = 0.5;
_this.useRGBColor = true;
_this.enableNoise = false;
_this._fovMultiplier = 1;
_this.useEquirectangularFOV = false;
_this._maxSimultaneousLights = 4;
_this.maxSimultaneousLights = 4;
_this._imageProcessingObserver = null;
_this.switchToBGR = false;
_this._renderTargets = new BABYLON2.SmartArray(16);
_this._reflectionControls = BABYLON2.Vector4.Zero();
_this._white = BABYLON2.Color3.White();
_this._primaryShadowColor = BABYLON2.Color3.Black();
_this._primaryHighlightColor = BABYLON2.Color3.Black();
_this._attachImageProcessingConfiguration(null);
_this.getRenderTargetTextures = function() {
_this._renderTargets.reset();
if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
_this._renderTargets.push(_this._diffuseTexture);
}
if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
_this._renderTargets.push(_this._reflectionTexture);
}
return _this._renderTargets;
};
return _this;
}
Object.defineProperty(BackgroundMaterial2.prototype, "_perceptualColor", {
/**
* Experimental Internal Use Only.
*
* Key light Color in "perceptual value" meaning the color you would like to see on screen.
* This acts as a helper to set the primary color to a more "human friendly" value.
* Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
* output color as close as possible from the chosen value.
* (This does not account for contrast color grading and color curves as they are considered post effect and not directly
* part of lighting setup.)
*/
get: function() {
return this.__perceptualColor;
},
set: function(value) {
this.__perceptualColor = value;
this._computePrimaryColorFromPerceptualColor();
this._markAllSubMeshesAsLightsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "primaryColorShadowLevel", {
/**
* Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
* The color opposite to the primary color is used at the level chosen to define what the black area would look.
*/
get: function() {
return this._primaryColorShadowLevel;
},
set: function(value) {
this._primaryColorShadowLevel = value;
this._computePrimaryColors();
this._markAllSubMeshesAsLightsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "primaryColorHighlightLevel", {
/**
* Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
* The primary color is used at the level chosen to define what the white area would look.
*/
get: function() {
return this._primaryColorHighlightLevel;
},
set: function(value) {
this._primaryColorHighlightLevel = value;
this._computePrimaryColors();
this._markAllSubMeshesAsLightsDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "reflectionStandardFresnelWeight", {
/**
* Sets the reflection reflectance fresnel values according to the default standard
* empirically know to work well :-)
*/
set: function(value) {
var reflectionWeight = value;
if (reflectionWeight < 0.5) {
reflectionWeight = reflectionWeight * 2;
this.reflectionReflectance0 = BackgroundMaterial2.StandardReflectance0 * reflectionWeight;
this.reflectionReflectance90 = BackgroundMaterial2.StandardReflectance90 * reflectionWeight;
} else {
reflectionWeight = reflectionWeight * 2 - 1;
this.reflectionReflectance0 = BackgroundMaterial2.StandardReflectance0 + (1 - BackgroundMaterial2.StandardReflectance0) * reflectionWeight;
this.reflectionReflectance90 = BackgroundMaterial2.StandardReflectance90 + (1 - BackgroundMaterial2.StandardReflectance90) * reflectionWeight;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "fovMultiplier", {
/**
* The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
* Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
* Recommended to be keep at 1.0 except for special cases.
*/
get: function() {
return this._fovMultiplier;
},
set: function(value) {
if (isNaN(value)) {
value = 1;
}
this._fovMultiplier = Math.max(0, Math.min(2, value));
},
enumerable: true,
configurable: true
});
BackgroundMaterial2.prototype._attachImageProcessingConfiguration = function(configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
} else {
this._imageProcessingConfiguration = configuration;
}
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function(conf) {
_this._computePrimaryColorFromPerceptualColor();
_this._markAllSubMeshesAsImageProcessingDirty();
});
}
};
Object.defineProperty(BackgroundMaterial2.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function() {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function(value) {
this._attachImageProcessingConfiguration(value);
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "cameraColorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "cameraColorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function() {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function(value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "cameraToneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function() {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function(value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "cameraExposure", {
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
get: function() {
return this._imageProcessingConfiguration.exposure;
},
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
set: function(value) {
this._imageProcessingConfiguration.exposure = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "cameraContrast", {
/**
* Gets The camera contrast used on this material.
*/
get: function() {
return this._imageProcessingConfiguration.contrast;
},
/**
* Sets The camera contrast used on this material.
*/
set: function(value) {
this._imageProcessingConfiguration.contrast = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "cameraColorGradingTexture", {
/**
* Gets the Color Grading 2D Lookup Texture.
*/
get: function() {
return this._imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets the Color Grading 2D Lookup Texture.
*/
set: function(value) {
this.imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "cameraColorCurves", {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
get: function() {
return this.imageProcessingConfiguration.colorCurves;
},
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
set: function(value) {
this.imageProcessingConfiguration.colorCurves = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BackgroundMaterial2.prototype, "hasRenderTargetTextures", {
/**
* Gets a boolean indicating that current material needs to register RTT
*/
get: function() {
if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
return true;
}
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
return true;
}
return false;
},
enumerable: true,
configurable: true
});
BackgroundMaterial2.prototype.needAlphaTesting = function() {
return true;
};
BackgroundMaterial2.prototype.needAlphaBlending = function() {
return this.alpha < 0 || this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
};
BackgroundMaterial2.prototype.isReadyForSubMesh = function(mesh2, subMesh, useInstances) {
var _this = this;
if (useInstances === void 0) {
useInstances = false;
}
if (subMesh.effect && this.isFrozen) {
if (this._wasPreviouslyReady) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new BackgroundMaterialDefines();
}
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!this.checkReadyOnEveryCall && subMesh.effect) {
if (defines._renderId === scene.getRenderId()) {
return true;
}
}
var engine = scene.getEngine();
BABYLON2.MaterialHelper.PrepareDefinesForLights(scene, mesh2, defines, false, this._maxSimultaneousLights);
defines._needNormals = true;
if (defines._areTexturesDirty) {
defines._needUVs = false;
if (scene.texturesEnabled) {
if (scene.getEngine().getCaps().textureLOD) {
defines.TEXTURELODSUPPORT = true;
}
if (this._diffuseTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
if (!this._diffuseTexture.isReadyOrNotBlocking()) {
return false;
}
BABYLON2.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
defines.OPACITYFRESNEL = this._opacityFresnel;
} else {
defines.DIFFUSE = false;
defines.DIFFUSEHASALPHA = false;
defines.GAMMADIFFUSE = false;
defines.OPACITYFRESNEL = false;
}
var reflectionTexture = this._reflectionTexture;
if (reflectionTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
if (!reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
defines.REFLECTION = true;
defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
defines.RGBDREFLECTION = reflectionTexture.isRGBD;
defines.REFLECTIONBLUR = this._reflectionBlur > 0;
defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
defines.REFLECTIONBGR = this.switchToBGR;
if (reflectionTexture.coordinatesMode === BABYLON2.Texture.INVCUBIC_MODE) {
defines.INVERTCUBICMAP = true;
}
defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
switch (reflectionTexture.coordinatesMode) {
case BABYLON2.Texture.EXPLICIT_MODE:
defines.REFLECTIONMAP_EXPLICIT = true;
break;
case BABYLON2.Texture.PLANAR_MODE:
defines.REFLECTIONMAP_PLANAR = true;
break;
case BABYLON2.Texture.PROJECTION_MODE:
defines.REFLECTIONMAP_PROJECTION = true;
break;
case BABYLON2.Texture.SKYBOX_MODE:
defines.REFLECTIONMAP_SKYBOX = true;
defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
break;
case BABYLON2.Texture.SPHERICAL_MODE:
defines.REFLECTIONMAP_SPHERICAL = true;
break;
case BABYLON2.Texture.EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
break;
case BABYLON2.Texture.FIXED_EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
break;
case BABYLON2.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
break;
case BABYLON2.Texture.CUBIC_MODE:
case BABYLON2.Texture.INVCUBIC_MODE:
default:
defines.REFLECTIONMAP_CUBIC = true;
break;
}
if (this.reflectionFresnel) {
defines.REFLECTIONFRESNEL = true;
defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
this._reflectionControls.x = this.reflectionAmount;
this._reflectionControls.y = this.reflectionReflectance0;
this._reflectionControls.z = this.reflectionReflectance90;
this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
} else {
defines.REFLECTIONFRESNEL = false;
defines.REFLECTIONFALLOFF = false;
}
} else {
defines.REFLECTION = false;
defines.REFLECTIONFRESNEL = false;
defines.REFLECTIONFALLOFF = false;
defines.REFLECTIONBLUR = false;
defines.REFLECTIONMAP_3D = false;
defines.REFLECTIONMAP_SPHERICAL = false;
defines.REFLECTIONMAP_PLANAR = false;
defines.REFLECTIONMAP_CUBIC = false;
defines.REFLECTIONMAP_PROJECTION = false;
defines.REFLECTIONMAP_SKYBOX = false;
defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
defines.REFLECTIONMAP_EXPLICIT = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
defines.INVERTCUBICMAP = false;
defines.REFLECTIONMAP_OPPOSITEZ = false;
defines.LODINREFLECTIONALPHA = false;
defines.GAMMAREFLECTION = false;
defines.RGBDREFLECTION = false;
}
}
defines.PREMULTIPLYALPHA = this.alphaMode === BABYLON2.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON2.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
defines.USERGBCOLOR = this._useRGBColor;
defines.NOISE = this._enableNoise;
}
if (defines._areLightsDirty) {
defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
this._imageProcessingConfiguration.prepareDefines(defines);
}
BABYLON2.MaterialHelper.PrepareDefinesForMisc(mesh2, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh2), defines);
BABYLON2.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
if (BABYLON2.MaterialHelper.PrepareDefinesForAttributes(mesh2, defines, false, true, false)) {
if (mesh2) {
if (!scene.getEngine().getCaps().standardDerivatives && !mesh2.isVerticesDataPresent(BABYLON2.VertexBuffer.NormalKind)) {
mesh2.createNormals(true);
BABYLON2.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh2.name);
}
}
}
if (defines.isDirty) {
defines.markAsProcessed();
scene.resetCachedMaterial();
var fallbacks = new BABYLON2.EffectFallbacks();
if (defines.FOG) {
fallbacks.addFallback(0, "FOG");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(1, "POINTSIZE");
}
BABYLON2.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
if (defines.NUM_BONE_INFLUENCERS > 0) {
fallbacks.addCPUSkinningFallback(0, mesh2);
}
var attribs = [BABYLON2.VertexBuffer.PositionKind];
if (defines.NORMAL) {
attribs.push(BABYLON2.VertexBuffer.NormalKind);
}
if (defines.UV1) {
attribs.push(BABYLON2.VertexBuffer.UVKind);
}
if (defines.UV2) {
attribs.push(BABYLON2.VertexBuffer.UV2Kind);
}
BABYLON2.MaterialHelper.PrepareAttributesForBones(attribs, mesh2, defines, fallbacks);
BABYLON2.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
var uniforms = [
"world",
"view",
"viewProjection",
"vEyePosition",
"vLightsType",
"vFogInfos",
"vFogColor",
"pointSize",
"vClipPlane",
"vClipPlane2",
"vClipPlane3",
"vClipPlane4",
"mBones",
"vPrimaryColor",
"vPrimaryColorShadow",
"vReflectionInfos",
"reflectionMatrix",
"vReflectionMicrosurfaceInfos",
"fFovMultiplier",
"shadowLevel",
"alpha",
"vBackgroundCenter",
"vReflectionControl",
"vDiffuseInfos",
"diffuseMatrix"
];
var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
var uniformBuffers = ["Material", "Scene"];
if (BABYLON2.ImageProcessingConfiguration) {
BABYLON2.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
BABYLON2.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
}
BABYLON2.MaterialHelper.PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers,
defines,
maxSimultaneousLights: this._maxSimultaneousLights
});
var onCompiled = function(effect) {
if (_this.onCompiled) {
_this.onCompiled(effect);
}
_this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
};
var join = defines.toString();
subMesh.setEffect(scene.getEngine().createEffect("background", {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers,
defines: join,
fallbacks,
onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
}, engine), defines);
this.buildUniformLayout();
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
this._wasPreviouslyReady = true;
return true;
};
BackgroundMaterial2.prototype._computePrimaryColorFromPerceptualColor = function() {
if (!this.__perceptualColor) {
return;
}
this._primaryColor.copyFrom(this.__perceptualColor);
this._primaryColor.toLinearSpaceToRef(this._primaryColor);
if (this._imageProcessingConfiguration) {
this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
}
this._computePrimaryColors();
};
BackgroundMaterial2.prototype._computePrimaryColors = function() {
if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
return;
}
this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
};
BackgroundMaterial2.prototype.buildUniformLayout = function() {
this._uniformBuffer.addUniform("vPrimaryColor", 4);
this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
this._uniformBuffer.addUniform("vDiffuseInfos", 2);
this._uniformBuffer.addUniform("vReflectionInfos", 2);
this._uniformBuffer.addUniform("diffuseMatrix", 16);
this._uniformBuffer.addUniform("reflectionMatrix", 16);
this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
this._uniformBuffer.addUniform("fFovMultiplier", 1);
this._uniformBuffer.addUniform("pointSize", 1);
this._uniformBuffer.addUniform("shadowLevel", 1);
this._uniformBuffer.addUniform("alpha", 1);
this._uniformBuffer.addUniform("vBackgroundCenter", 3);
this._uniformBuffer.addUniform("vReflectionControl", 4);
this._uniformBuffer.create();
};
BackgroundMaterial2.prototype.unbind = function() {
if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
this._uniformBuffer.setTexture("diffuseSampler", null);
}
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._uniformBuffer.setTexture("reflectionSampler", null);
}
_super.prototype.unbind.call(this);
};
BackgroundMaterial2.prototype.bindOnlyWorldMatrix = function(world) {
this._activeEffect.setMatrix("world", world);
};
BackgroundMaterial2.prototype.bindForSubMesh = function(world, mesh2, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
this.bindOnlyWorldMatrix(world);
BABYLON2.MaterialHelper.BindBonesParameters(mesh2, this._activeEffect);
var mustRebind = this._mustRebind(scene, effect, mesh2.visibility);
if (mustRebind) {
this._uniformBuffer.bindToEffect(effect, "Material");
this.bindViewProjection(effect);
var reflectionTexture = this._reflectionTexture;
if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
if (scene.texturesEnabled) {
if (this._diffuseTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
BABYLON2.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
}
if (reflectionTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
}
}
if (this.shadowLevel > 0) {
this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
}
this._uniformBuffer.updateFloat("alpha", this.alpha);
if (this.pointsCloud) {
this._uniformBuffer.updateFloat("pointSize", this.pointSize);
}
if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1);
this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1);
} else {
this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1);
}
}
this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
if (scene.texturesEnabled) {
if (this._diffuseTexture && BABYLON2.StandardMaterial.DiffuseTextureEnabled) {
this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
}
if (reflectionTexture && BABYLON2.StandardMaterial.ReflectionTextureEnabled) {
if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
} else if (!defines.REFLECTIONBLUR) {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
} else {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
}
if (defines.REFLECTIONFRESNEL) {
this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
}
}
}
BABYLON2.MaterialHelper.BindClipPlane(this._activeEffect, scene);
BABYLON2.MaterialHelper.BindEyePosition(effect, scene);
}
if (mustRebind || !this.isFrozen) {
if (scene.lightsEnabled) {
BABYLON2.MaterialHelper.BindLights(scene, mesh2, this._activeEffect, defines, this._maxSimultaneousLights, false);
}
this.bindView(effect);
BABYLON2.MaterialHelper.BindFogParameters(scene, mesh2, this._activeEffect, true);
if (this._imageProcessingConfiguration) {
this._imageProcessingConfiguration.bind(this._activeEffect);
}
}
this._uniformBuffer.update();
this._afterBind(mesh2, this._activeEffect);
};
BackgroundMaterial2.prototype.dispose = function(forceDisposeEffect, forceDisposeTextures) {
if (forceDisposeEffect === void 0) {
forceDisposeEffect = false;
}
if (forceDisposeTextures === void 0) {
forceDisposeTextures = false;
}
if (forceDisposeTextures) {
if (this.diffuseTexture) {
this.diffuseTexture.dispose();
}
if (this.reflectionTexture) {
this.reflectionTexture.dispose();
}
}
this._renderTargets.dispose();
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
_super.prototype.dispose.call(this, forceDisposeEffect);
};
BackgroundMaterial2.prototype.clone = function(name) {
var _this = this;
return BABYLON2.SerializationHelper.Clone(function() {
return new BackgroundMaterial2(name, _this.getScene());
}, this);
};
BackgroundMaterial2.prototype.serialize = function() {
var serializationObject = BABYLON2.SerializationHelper.Serialize(this);
serializationObject.customType = "BABYLON.BackgroundMaterial";
return serializationObject;
};
BackgroundMaterial2.prototype.getClassName = function() {
return "BackgroundMaterial";
};
BackgroundMaterial2.Parse = function(source, scene, rootUrl) {
return BABYLON2.SerializationHelper.Parse(function() {
return new BackgroundMaterial2(source.name, scene);
}, source, scene, rootUrl);
};
BackgroundMaterial2.StandardReflectance0 = 0.05;
BackgroundMaterial2.StandardReflectance90 = 0.5;
__decorate([
BABYLON2.serializeAsColor3()
], BackgroundMaterial2.prototype, "_primaryColor", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial2.prototype, "primaryColor", void 0);
__decorate([
BABYLON2.serializeAsColor3()
], BackgroundMaterial2.prototype, "__perceptualColor", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_primaryColorShadowLevel", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_primaryColorHighlightLevel", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial2.prototype, "primaryColorHighlightLevel", null);
__decorate([
BABYLON2.serializeAsTexture()
], BackgroundMaterial2.prototype, "_reflectionTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "reflectionTexture", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_reflectionBlur", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "reflectionBlur", void 0);
__decorate([
BABYLON2.serializeAsTexture()
], BackgroundMaterial2.prototype, "_diffuseTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "diffuseTexture", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "shadowLights", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_shadowLevel", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "shadowLevel", void 0);
__decorate([
BABYLON2.serializeAsVector3()
], BackgroundMaterial2.prototype, "_sceneCenter", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "sceneCenter", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_opacityFresnel", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "opacityFresnel", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_reflectionFresnel", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "reflectionFresnel", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_reflectionFalloffDistance", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "reflectionFalloffDistance", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_reflectionAmount", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "reflectionAmount", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_reflectionReflectance0", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "reflectionReflectance0", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_reflectionReflectance90", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "reflectionReflectance90", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_useRGBColor", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "useRGBColor", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_enableNoise", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "enableNoise", void 0);
__decorate([
BABYLON2.serialize()
], BackgroundMaterial2.prototype, "_maxSimultaneousLights", void 0);
__decorate([
BABYLON2.expandToProperty("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial2.prototype, "maxSimultaneousLights", void 0);
__decorate([
BABYLON2.serializeAsImageProcessingConfiguration()
], BackgroundMaterial2.prototype, "_imageProcessingConfiguration", void 0);
return BackgroundMaterial2;
}(BABYLON2.PushMaterial)
);
BABYLON2.BackgroundMaterial = BackgroundMaterial;
})(BABYLON || (BABYLON = {}));
var __assign = function() {
__assign = Object.assign || function(t) {
for (var s, i2 = 1, n = arguments.length; i2 < n; i2++) {
s = arguments[i2];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var BABYLON;
(function(BABYLON2) {
var EnvironmentHelper = (
/** @class */
function() {
function EnvironmentHelper2(options, scene) {
var _this = this;
this._errorHandler = function(message, exception) {
_this.onErrorObservable.notifyObservers({ message, exception });
};
this._options = __assign({}, EnvironmentHelper2._getDefaultOptions(), options);
this._scene = scene;
this.onErrorObservable = new BABYLON2.Observable();
this._setupBackground();
this._setupImageProcessing();
}
EnvironmentHelper2._getDefaultOptions = function() {
return {
createGround: true,
groundSize: 15,
groundTexture: this._groundTextureCDNUrl,
groundColor: new BABYLON2.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
groundOpacity: 0.9,
enableGroundShadow: true,
groundShadowLevel: 0.5,
enableGroundMirror: false,
groundMirrorSizeRatio: 0.3,
groundMirrorBlurKernel: 64,
groundMirrorAmount: 1,
groundMirrorFresnelWeight: 1,
groundMirrorFallOffDistance: 0,
groundMirrorTextureType: BABYLON2.Engine.TEXTURETYPE_UNSIGNED_INT,
groundYBias: 1e-5,
createSkybox: true,
skyboxSize: 20,
skyboxTexture: this._skyboxTextureCDNUrl,
skyboxColor: new BABYLON2.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
backgroundYRotation: 0,
sizeAuto: true,
rootPosition: BABYLON2.Vector3.Zero(),
setupImageProcessing: true,
environmentTexture: this._environmentTextureCDNUrl,
cameraExposure: 0.8,
cameraContrast: 1.2,
toneMappingEnabled: true
};
};
Object.defineProperty(EnvironmentHelper2.prototype, "rootMesh", {
/**
* Gets the root mesh created by the helper.
*/
get: function() {
return this._rootMesh;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "skybox", {
/**
* Gets the skybox created by the helper.
*/
get: function() {
return this._skybox;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "skyboxTexture", {
/**
* Gets the skybox texture created by the helper.
*/
get: function() {
return this._skyboxTexture;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "skyboxMaterial", {
/**
* Gets the skybox material created by the helper.
*/
get: function() {
return this._skyboxMaterial;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "ground", {
/**
* Gets the ground mesh created by the helper.
*/
get: function() {
return this._ground;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "groundTexture", {
/**
* Gets the ground texture created by the helper.
*/
get: function() {
return this._groundTexture;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "groundMirror", {
/**
* Gets the ground mirror created by the helper.
*/
get: function() {
return this._groundMirror;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "groundMirrorRenderList", {
/**
* Gets the ground mirror render list to helps pushing the meshes
* you wish in the ground reflection.
*/
get: function() {
if (this._groundMirror) {
return this._groundMirror.renderList;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(EnvironmentHelper2.prototype, "groundMaterial", {
/**
* Gets the ground material created by the helper.
*/
get: function() {
return this._groundMaterial;
},
enumerable: true,
configurable: true
});
EnvironmentHelper2.prototype.updateOptions = function(options) {
var newOptions = __assign({}, this._options, options);
if (this._ground && !newOptions.createGround) {
this._ground.dispose();
this._ground = null;
}
if (this._groundMaterial && !newOptions.createGround) {
this._groundMaterial.dispose();
this._groundMaterial = null;
}
if (this._groundTexture) {
if (this._options.groundTexture != newOptions.groundTexture) {
this._groundTexture.dispose();
this._groundTexture = null;
}
}
if (this._skybox && !newOptions.createSkybox) {
this._skybox.dispose();
this._skybox = null;
}
if (this._skyboxMaterial && !newOptions.createSkybox) {
this._skyboxMaterial.dispose();
this._skyboxMaterial = null;
}
if (this._skyboxTexture) {
if (this._options.skyboxTexture != newOptions.skyboxTexture) {
this._skyboxTexture.dispose();
this._skyboxTexture = null;
}
}
if (this._groundMirror && !newOptions.enableGroundMirror) {
this._groundMirror.dispose();
this._groundMirror = null;
}
if (this._scene.environmentTexture) {
if (this._options.environmentTexture != newOptions.environmentTexture) {
this._scene.environmentTexture.dispose();
}
}
this._options = newOptions;
this._setupBackground();
this._setupImageProcessing();
};
EnvironmentHelper2.prototype.setMainColor = function(color) {
if (this.groundMaterial) {
this.groundMaterial.primaryColor = color;
}
if (this.skyboxMaterial) {
this.skyboxMaterial.primaryColor = color;
}
if (this.groundMirror) {
this.groundMirror.clearColor = new BABYLON2.Color4(color.r, color.g, color.b, 1);
}
};
EnvironmentHelper2.prototype._setupImageProcessing = function() {
if (this._options.setupImageProcessing) {
this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
this._setupEnvironmentTexture();
}
};
EnvironmentHelper2.prototype._setupEnvironmentTexture = function() {
if (this._scene.environmentTexture) {
return;
}
if (this._options.environmentTexture instanceof BABYLON2.BaseTexture) {
this._scene.environmentTexture = this._options.environmentTexture;
return;
}
var environmentTexture = BABYLON2.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
this._scene.environmentTexture = environmentTexture;
};
EnvironmentHelper2.prototype._setupBackground = function() {
if (!this._rootMesh) {
this._rootMesh = new BABYLON2.Mesh("BackgroundHelper", this._scene);
}
this._rootMesh.rotation.y = this._options.backgroundYRotation;
var sceneSize = this._getSceneSize();
if (this._options.createGround) {
this._setupGround(sceneSize);
this._setupGroundMaterial();
this._setupGroundDiffuseTexture();
if (this._options.enableGroundMirror) {
this._setupGroundMirrorTexture(sceneSize);
}
this._setupMirrorInGroundMaterial();
}
if (this._options.createSkybox) {
this._setupSkybox(sceneSize);
this._setupSkyboxMaterial();
this._setupSkyboxReflectionTexture();
}
this._rootMesh.position.x = sceneSize.rootPosition.x;
this._rootMesh.position.z = sceneSize.rootPosition.z;
this._rootMesh.position.y = sceneSize.rootPosition.y;
};
EnvironmentHelper2.prototype._getSceneSize = function() {
var _this = this;
var groundSize = this._options.groundSize;
var skyboxSize = this._options.skyboxSize;
var rootPosition = this._options.rootPosition;
if (!this._scene.meshes || this._scene.meshes.length === 1) {
return { groundSize, skyboxSize, rootPosition };
}
var sceneExtends = this._scene.getWorldExtends(function(mesh2) {
return mesh2 !== _this._ground && mesh2 !== _this._rootMesh && mesh2 !== _this._skybox;
});
var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
if (this._options.sizeAuto) {
if (this._scene.activeCamera instanceof BABYLON2.ArcRotateCamera && this._scene.activeCamera.upperRadiusLimit) {
groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
skyboxSize = groundSize;
}
var sceneDiagonalLenght = sceneDiagonal.length();
if (sceneDiagonalLenght > groundSize) {
groundSize = sceneDiagonalLenght * 2;
skyboxSize = groundSize;
}
groundSize *= 1.1;
skyboxSize *= 1.5;
rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
}
return { groundSize, skyboxSize, rootPosition };
};
EnvironmentHelper2.prototype._setupGround = function(sceneSize) {
var _this = this;
if (!this._ground || this._ground.isDisposed()) {
this._ground = BABYLON2.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
this._ground.rotation.x = Math.PI / 2;
this._ground.parent = this._rootMesh;
this._ground.onDisposeObservable.add(function() {
_this._ground = null;
});
}
this._ground.receiveShadows = this._options.enableGroundShadow;
};
EnvironmentHelper2.prototype._setupGroundMaterial = function() {
if (!this._groundMaterial) {
this._groundMaterial = new BABYLON2.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
}
this._groundMaterial.alpha = this._options.groundOpacity;
this._groundMaterial.alphaMode = BABYLON2.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
this._groundMaterial.primaryColor = this._options.groundColor;
this._groundMaterial.useRGBColor = false;
this._groundMaterial.enableNoise = true;
if (this._ground) {
this._ground.material = this._groundMaterial;
}
};
EnvironmentHelper2.prototype._setupGroundDiffuseTexture = function() {
if (!this._groundMaterial) {
return;
}
if (this._groundTexture) {
return;
}
if (this._options.groundTexture instanceof BABYLON2.BaseTexture) {
this._groundMaterial.diffuseTexture = this._options.groundTexture;
return;
}
var diffuseTexture = new BABYLON2.Texture(this._options.groundTexture, this._scene, void 0, void 0, void 0, void 0, this._errorHandler);
diffuseTexture.gammaSpace = false;
diffuseTexture.hasAlpha = true;
this._groundMaterial.diffuseTexture = diffuseTexture;
};
EnvironmentHelper2.prototype._setupGroundMirrorTexture = function(sceneSize) {
var wrapping = BABYLON2.Texture.CLAMP_ADDRESSMODE;
if (!this._groundMirror) {
this._groundMirror = new BABYLON2.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON2.Texture.BILINEAR_SAMPLINGMODE, true);
this._groundMirror.mirrorPlane = new BABYLON2.Plane(0, -1, 0, sceneSize.rootPosition.y);
this._groundMirror.anisotropicFilteringLevel = 1;
this._groundMirror.wrapU = wrapping;
this._groundMirror.wrapV = wrapping;
this._groundMirror.gammaSpace = false;
if (this._groundMirror.renderList) {
for (var i2 = 0; i2 < this._scene.meshes.length; i2++) {
var mesh2 = this._scene.meshes[i2];
if (mesh2 !== this._ground && mesh2 !== this._skybox && mesh2 !== this._rootMesh) {
this._groundMirror.renderList.push(mesh2);
}
}
}
}
this._groundMirror.clearColor = new BABYLON2.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
};
EnvironmentHelper2.prototype._setupMirrorInGroundMaterial = function() {
if (this._groundMaterial) {
this._groundMaterial.reflectionTexture = this._groundMirror;
this._groundMaterial.reflectionFresnel = true;
this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
}
};
EnvironmentHelper2.prototype._setupSkybox = function(sceneSize) {
var _this = this;
if (!this._skybox || this._skybox.isDisposed()) {
this._skybox = BABYLON2.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, void 0, BABYLON2.Mesh.BACKSIDE);
this._skybox.onDisposeObservable.add(function() {
_this._skybox = null;
});
}
this._skybox.parent = this._rootMesh;
};
EnvironmentHelper2.prototype._setupSkyboxMaterial = function() {
if (!this._skybox) {
return;
}
if (!this._skyboxMaterial) {
this._skyboxMaterial = new BABYLON2.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
}
this._skyboxMaterial.useRGBColor = false;
this._skyboxMaterial.primaryColor = this._options.skyboxColor;
this._skyboxMaterial.enableNoise = true;
this._skybox.material = this._skyboxMaterial;
};
EnvironmentHelper2.prototype._setupSkyboxReflectionTexture = function() {
if (!this._skyboxMaterial) {
return;
}
if (this._skyboxTexture) {
return;
}
if (this._options.skyboxTexture instanceof BABYLON2.BaseTexture) {
this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
return;
}
this._skyboxTexture = new BABYLON2.CubeTexture(this._options.skyboxTexture, this._scene, void 0, void 0, void 0, void 0, this._errorHandler);
this._skyboxTexture.coordinatesMode = BABYLON2.Texture.SKYBOX_MODE;
this._skyboxTexture.gammaSpace = false;
this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
};
EnvironmentHelper2.prototype.dispose = function() {
if (this._groundMaterial) {
this._groundMaterial.dispose(true, true);
}
if (this._skyboxMaterial) {
this._skyboxMaterial.dispose(true, true);
}
this._rootMesh.dispose(false);
};
EnvironmentHelper2._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
EnvironmentHelper2._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
EnvironmentHelper2._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
return EnvironmentHelper2;
}()
);
BABYLON2.EnvironmentHelper = EnvironmentHelper;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var _OcclusionDataStorage = (
/** @class */
function() {
function _OcclusionDataStorage2() {
this.occlusionInternalRetryCounter = 0;
this.isOcclusionQueryInProgress = false;
this.isOccluded = false;
this.occlusionRetryCount = -1;
this.occlusionType = BABYLON2.AbstractMesh.OCCLUSION_TYPE_NONE;
this.occlusionQueryAlgorithmType = BABYLON2.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
}
return _OcclusionDataStorage2;
}()
);
BABYLON2.Engine.prototype.createQuery = function() {
return this._gl.createQuery();
};
BABYLON2.Engine.prototype.deleteQuery = function(query) {
this._gl.deleteQuery(query);
return this;
};
BABYLON2.Engine.prototype.isQueryResultAvailable = function(query) {
return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
};
BABYLON2.Engine.prototype.getQueryResult = function(query) {
return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
};
BABYLON2.Engine.prototype.beginOcclusionQuery = function(algorithmType, query) {
var glAlgorithm = this._getGlAlgorithmType(algorithmType);
this._gl.beginQuery(glAlgorithm, query);
return this;
};
BABYLON2.Engine.prototype.endOcclusionQuery = function(algorithmType) {
var glAlgorithm = this._getGlAlgorithmType(algorithmType);
this._gl.endQuery(glAlgorithm);
return this;
};
BABYLON2.Engine.prototype._createTimeQuery = function() {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.createQueryEXT) {
return timerQuery.createQueryEXT();
}
return this.createQuery();
};
BABYLON2.Engine.prototype._deleteTimeQuery = function(query) {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.deleteQueryEXT) {
timerQuery.deleteQueryEXT(query);
return;
}
this.deleteQuery(query);
};
BABYLON2.Engine.prototype._getTimeQueryResult = function(query) {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.getQueryObjectEXT) {
return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
}
return this.getQueryResult(query);
};
BABYLON2.Engine.prototype._getTimeQueryAvailability = function(query) {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.getQueryObjectEXT) {
return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
}
return this.isQueryResultAvailable(query);
};
BABYLON2.Engine.prototype.startTimeQuery = function() {
var caps = this.getCaps();
var timerQuery = caps.timerQuery;
if (!timerQuery) {
return null;
}
var token = new BABYLON2._TimeToken();
this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
if (caps.canUseTimestampForTimerQuery) {
token._startTimeQuery = this._createTimeQuery();
timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
} else {
if (this._currentNonTimestampToken) {
return this._currentNonTimestampToken;
}
token._timeElapsedQuery = this._createTimeQuery();
if (timerQuery.beginQueryEXT) {
timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
} else {
this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
}
this._currentNonTimestampToken = token;
}
return token;
};
BABYLON2.Engine.prototype.endTimeQuery = function(token) {
var caps = this.getCaps();
var timerQuery = caps.timerQuery;
if (!timerQuery || !token) {
return -1;
}
if (caps.canUseTimestampForTimerQuery) {
if (!token._startTimeQuery) {
return -1;
}
if (!token._endTimeQuery) {
token._endTimeQuery = this._createTimeQuery();
timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
}
} else if (!token._timeElapsedQueryEnded) {
if (!token._timeElapsedQuery) {
return -1;
}
if (timerQuery.endQueryEXT) {
timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
} else {
this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
}
token._timeElapsedQueryEnded = true;
}
var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
var available = false;
if (token._endTimeQuery) {
available = this._getTimeQueryAvailability(token._endTimeQuery);
} else if (token._timeElapsedQuery) {
available = this._getTimeQueryAvailability(token._timeElapsedQuery);
}
if (available && !disjoint) {
var result = 0;
if (caps.canUseTimestampForTimerQuery) {
if (!token._startTimeQuery || !token._endTimeQuery) {
return -1;
}
var timeStart = this._getTimeQueryResult(token._startTimeQuery);
var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
result = timeEnd - timeStart;
this._deleteTimeQuery(token._startTimeQuery);
this._deleteTimeQuery(token._endTimeQuery);
token._startTimeQuery = null;
token._endTimeQuery = null;
} else {
if (!token._timeElapsedQuery) {
return -1;
}
result = this._getTimeQueryResult(token._timeElapsedQuery);
this._deleteTimeQuery(token._timeElapsedQuery);
token._timeElapsedQuery = null;
token._timeElapsedQueryEnded = false;
this._currentNonTimestampToken = null;
}
return result;
}
return -1;
};
BABYLON2.Engine.prototype._getGlAlgorithmType = function(algorithmType) {
return algorithmType === BABYLON2.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
};
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
get: function() {
return this._occlusionDataStorage.isOcclusionQueryInProgress;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "_occlusionDataStorage", {
get: function() {
if (!this.__occlusionDataStorage) {
this.__occlusionDataStorage = new _OcclusionDataStorage();
}
return this.__occlusionDataStorage;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "isOccluded", {
get: function() {
return this._occlusionDataStorage.isOccluded;
},
set: function(value) {
this._occlusionDataStorage.isOccluded = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
get: function() {
return this._occlusionDataStorage.occlusionQueryAlgorithmType;
},
set: function(value) {
this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "occlusionType", {
get: function() {
return this._occlusionDataStorage.occlusionType;
},
set: function(value) {
this._occlusionDataStorage.occlusionType = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BABYLON2.AbstractMesh.prototype, "occlusionRetryCount", {
get: function() {
return this._occlusionDataStorage.occlusionRetryCount;
},
set: function(value) {
this._occlusionDataStorage.occlusionRetryCount = value;
},
enumerable: true,
configurable: true
});
BABYLON2.AbstractMesh.prototype._checkOcclusionQuery = function() {
var dataStorage = this._occlusionDataStorage;
if (dataStorage.occlusionType === BABYLON2.AbstractMesh.OCCLUSION_TYPE_NONE) {
dataStorage.isOccluded = false;
return false;
}
var engine = this.getEngine();
if (engine.webGLVersion < 2) {
dataStorage.isOccluded = false;
return false;
}
if (!engine.isQueryResultAvailable) {
dataStorage.isOccluded = false;
return false;
}
if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
if (isOcclusionQueryAvailable) {
var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
dataStorage.isOcclusionQueryInProgress = false;
dataStorage.occlusionInternalRetryCounter = 0;
dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
} else {
dataStorage.occlusionInternalRetryCounter++;
if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
dataStorage.isOcclusionQueryInProgress = false;
dataStorage.occlusionInternalRetryCounter = 0;
dataStorage.isOccluded = dataStorage.occlusionType === BABYLON2.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
} else {
return false;
}
}
}
var scene = this.getScene();
if (scene.getBoundingBoxRenderer) {
var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
if (!this._occlusionQuery) {
this._occlusionQuery = engine.createQuery();
}
engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
this._occlusionDataStorage.isOcclusionQueryInProgress = true;
}
return dataStorage.isOccluded;
};
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
var NoiseProceduralTexture = (
/** @class */
function(_super) {
__extends(NoiseProceduralTexture2, _super);
function NoiseProceduralTexture2(name, size, scene, fallbackTexture, generateMipMaps) {
if (size === void 0) {
size = 256;
}
if (scene === void 0) {
scene = BABYLON2.Engine.LastCreatedScene;
}
var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
_this._time = 0;
_this.brightness = 0.2;
_this.octaves = 3;
_this.persistence = 0.8;
_this.animationSpeedFactor = 1;
_this.autoClear = false;
_this._updateShaderUniforms();
return _this;
}
NoiseProceduralTexture2.prototype._updateShaderUniforms = function() {
var scene = this.getScene();
if (!scene) {
return;
}
this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
this.setFloat("brightness", this.brightness);
this.setFloat("persistence", this.persistence);
this.setFloat("timeScale", this._time);
};
NoiseProceduralTexture2.prototype._getDefines = function() {
return "#define OCTAVES " + (this.octaves | 0);
};
NoiseProceduralTexture2.prototype.render = function(useCameraPostProcess) {
this._updateShaderUniforms();
_super.prototype.render.call(this, useCameraPostProcess);
};
NoiseProceduralTexture2.prototype.serialize = function() {
var serializationObject = {};
serializationObject.customType = "BABYLON.NoiseProceduralTexture";
serializationObject.brightness = this.brightness;
serializationObject.octaves = this.octaves;
serializationObject.persistence = this.persistence;
serializationObject.animationSpeedFactor = this.animationSpeedFactor;
serializationObject.size = this.getSize().width;
serializationObject.generateMipMaps = this._generateMipMaps;
return serializationObject;
};
NoiseProceduralTexture2.Parse = function(parsedTexture, scene, rootUrl) {
var texture = new NoiseProceduralTexture2(parsedTexture.name, parsedTexture.size, scene, void 0, parsedTexture.generateMipMaps);
texture.brightness = parsedTexture.brightness;
texture.octaves = parsedTexture.octaves;
texture.persistence = parsedTexture.persistence;
texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
return texture;
};
return NoiseProceduralTexture2;
}(BABYLON2.ProceduralTexture)
);
BABYLON2.NoiseProceduralTexture = NoiseProceduralTexture;
})(BABYLON || (BABYLON = {}));
var __assign = function() {
__assign = Object.assign || function(t) {
for (var s, i2 = 1, n = arguments.length; i2 < n; i2++) {
s = arguments[i2];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var BABYLON;
(function(BABYLON2) {
var VideoRecorder = (
/** @class */
function() {
function VideoRecorder2(engine, options) {
if (options === void 0) {
options = null;
}
if (!VideoRecorder2.IsSupported(engine)) {
throw "Your browser does not support recording so far.";
}
var canvas2 = engine.getRenderingCanvas();
if (!canvas2) {
throw "The babylon engine must have a canvas to be recorded";
}
this._canvas = canvas2;
this._canvas.isRecording = false;
this._options = __assign({}, VideoRecorder2._defaultOptions, options);
var stream = this._canvas.captureStream(this._options.fps);
this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
this._mediaRecorder.onerror = this._handleError.bind(this);
this._mediaRecorder.onstop = this._handleStop.bind(this);
}
VideoRecorder2.IsSupported = function(engine) {
var canvas2 = engine.getRenderingCanvas();
return !!canvas2 && typeof canvas2.captureStream === "function";
};
Object.defineProperty(VideoRecorder2.prototype, "isRecording", {
/**
* True wether a recording is already in progress.
*/
get: function() {
return !!this._canvas && this._canvas.isRecording;
},
enumerable: true,
configurable: true
});
VideoRecorder2.prototype.stopRecording = function() {
if (!this._canvas || !this._mediaRecorder) {
return;
}
if (!this.isRecording) {
return;
}
this._canvas.isRecording = false;
this._mediaRecorder.stop();
};
VideoRecorder2.prototype.startRecording = function(fileName, maxDuration) {
var _this = this;
if (fileName === void 0) {
fileName = "babylonjs.webm";
}
if (maxDuration === void 0) {
maxDuration = 7;
}
if (!this._canvas || !this._mediaRecorder) {
throw "Recorder has already been disposed";
}
if (this.isRecording) {
throw "Recording already in progress";
}
if (maxDuration > 0) {
setTimeout(function() {
_this.stopRecording();
}, maxDuration * 1e3);
}
this._fileName = fileName;
this._recordedChunks = [];
this._resolve = null;
this._reject = null;
this._canvas.isRecording = true;
this._mediaRecorder.start(this._options.recordChunckSize);
return new Promise(function(resolve, reject) {
_this._resolve = resolve;
_this._reject = reject;
});
};
VideoRecorder2.prototype.dispose = function() {
this._canvas = null;
this._mediaRecorder = null;
this._recordedChunks = [];
this._fileName = null;
this._resolve = null;
this._reject = null;
};
VideoRecorder2.prototype._handleDataAvailable = function(event) {
if (event.data.size > 0) {
this._recordedChunks.push(event.data);
}
};
VideoRecorder2.prototype._handleError = function(event) {
this.stopRecording();
if (this._reject) {
this._reject(event.error);
} else {
throw new event.error();
}
};
VideoRecorder2.prototype._handleStop = function() {
this.stopRecording();
var superBuffer = new Blob(this._recordedChunks);
if (this._resolve) {
this._resolve(superBuffer);
}
window.URL.createObjectURL(superBuffer);
if (this._fileName) {
BABYLON2.Tools.Download(superBuffer, this._fileName);
}
};
VideoRecorder2._defaultOptions = {
mimeType: "video/webm",
fps: 25,
recordChunckSize: 3e3
};
return VideoRecorder2;
}()
);
BABYLON2.VideoRecorder = VideoRecorder;
})(BABYLON || (BABYLON = {}));
var BABYLON;
(function(BABYLON2) {
BABYLON2.Scene.prototype.createDefaultLight = function(replace) {
if (replace === void 0) {
replace = false;
}
if (replace) {
if (this.lights) {
for (var i2 = 0; i2 < this.lights.length; i2++) {
this.lights[i2].dispose();
}
}
}
if (this.lights.length === 0) {
new BABYLON2.HemisphericLight("default light", BABYLON2.Vector3.Up(), this);
}
};
BABYLON2.Scene.prototype.createDefaultCamera = function(createArcRotateCamera, replace, attachCameraControls) {
if (createArcRotateCamera === void 0) {
createArcRotateCamera = false;
}
if (replace === void 0) {
replace = false;
}
if (attachCameraControls === void 0) {
attachCameraControls = false;
}
if (replace) {
if (this.activeCamera) {
this.activeCamera.dispose();
this.activeCamera = null;
}
}
if (!this.activeCamera) {
var worldExtends = this.getWorldExtends();
var worldSize = worldExtends.max.subtract(worldExtends.min);
var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
var camera2;
var radius = worldSize.length() * 1.5;
if (!isFinite(radius)) {
radius = 1;
worldCenter.copyFromFloats(0, 0, 0);
}
if (createArcRotateCamera) {
var arcRotateCamera = new BABYLON2.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
arcRotateCamera.lowerRadiusLimit = radius * 0.01;
arcRotateCamera.wheelPrecision = 100 / radius;
camera2 = arcRotateCamera;
} else {
var freeCamera = new BABYLON2.FreeCamera("default camera", new BABYLON2.Vector3(worldCenter.x, worldCenter.y, -radius), this);
freeCamera.setTarget(worldCenter);
camera2 = freeCamera;
}
camera2.minZ = radius * 0.01;
camera2.maxZ = radius * 1e3;
camera2.speed = radius * 0.2;
this.activeCamera = camera2;
var canvas2 = this.getEngine().getRenderingCanvas();
if (attachCameraControls && canvas2) {
camera2.attachControl(canvas2);
}
}
};
BABYLON2.Scene.prototype.createDefaultCameraOrLight = function(createArcRotateCamera, replace, attachCameraControls) {
if (createArcRotateCamera === void 0) {
createArcRotateCamera = false;
}
if (replace === void 0) {
replace = false;
}
if (attachCameraControls === void 0) {
attachCameraControls = false;
}
this.createDefaultLight(replace);
this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
};
BABYLON2.Scene.prototype.createDefaultSkybox = function(environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
if (pbr === void 0) {
pbr = false;
}
if (scale === void 0) {
scale = 1e3;
}
if (blur === void 0) {
blur = 0;
}
if (setGlobalEnvTexture === void 0) {
setGlobalEnvTexture = true;
}
if (!environmentTexture) {
BABYLON2.Tools.Warn("Can not create default skybox without environment texture.");
return null;
}
if (setGlobalEnvTexture) {
if (environmentTexture) {
this.environmentTexture = environmentTexture;
}
}
var hdrSkybox = BABYLON2.Mesh.CreateBox("hdrSkyBox", scale, this);
if (pbr) {
var hdrSkyboxMaterial = new BABYLON2.PBRMaterial("skyBox", this);
hdrSkyboxMaterial.backFaceCulling = false;
hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
if (hdrSkyboxMaterial.reflectionTexture) {
hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON2.Texture.SKYBOX_MODE;
}
hdrSkyboxMaterial.microSurface = 1 - blur;
hdrSkyboxMaterial.disableLighting = true;
hdrSkyboxMaterial.twoSidedLighting = true;
hdrSkybox.infiniteDistance = true;
hdrSkybox.material = hdrSkyboxMaterial;
} else {
var skyboxMaterial = new BABYLON2.StandardMaterial("skyBox", this);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.reflectionTexture = environmentTexture.clone();
if (skyboxMaterial.reflectionTexture) {
skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON2.Texture.SKYBOX_MODE;
}
skyboxMaterial.disableLighting = true;
hdrSkybox.infiniteDistance = true;
hdrSkybox.material = skyboxMaterial;
}
return hdrSkybox;
};
BABYLON2.Scene.prototype.createDefaultEnvironment = function(options) {
if (BABYLON2.EnvironmentHelper) {
return new BABYLON2.EnvironmentHelper(options, this);
}
return null;
};
BABYLON2.Scene.prototype.createDefaultVRExperience = function(webVROptions) {
if (webVROptions === void 0) {
webVROptions = {};
}
return new BABYLON2.VRExperienceHelper(this, webVROptions);
};
})(BABYLON || (BABYLON = {}));
BABYLON.Effect.ShadersStore = { "defaultVertexShader": "#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include\n#include\n#include\n#include[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include\n#include\n#define CUSTOM_VERTEX_MAIN_END\n}\n", "defaultPixelShader": "#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#include\n#include\n#include\n#include\n#include\n#include\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include\n#include\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n", "pbrVertexShader": "precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n#include\n\n#include\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include\n}", "pbrPixelShader": "#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include\n#include\n#include\n\n#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include\nvoid main(void) {\n#include\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include\n#include(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}", "rgbdEncodePixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}", "rgbdDecodePixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}", "spritesVertexShader": "\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}", "spritesPixelShader": "uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include\ngl_FragColor=color;\n}", "particlesVertexShader": "\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include\n}", "particlesPixelShader": "\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include\n#include\n#include\n#include\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}", "colorVertexShader": "\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include\n\n#include\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}", "colorPixelShader": "#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}", "gpuRenderParticlesVertexShader": "#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include\n}", "gpuRenderParticlesPixelShader": "#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include \n#include\n#include\n#include\nvoid main() {\n#include \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n", "gpuUpdateParticlesVertexShader": "#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}", "gpuUpdateParticlesPixelShader": "#version 300 es\nvoid main() {\ndiscard;\n}\n", "postprocessVertexShader": "\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}", "passPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}", "shadowMapVertexShader": "\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\n#include\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}", "shadowMapPixelShader": "#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}", "depthBoxBlurPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}", "proceduralVertexShader": "\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}", "depthVertexShader": "\nattribute vec3 position;\n#include\n\n#include\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}", "depthPixelShader": "#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}", "geometryVertexShader": "precision highp float;\nprecision highp int;\n#include\n#include\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include\n#include\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}", "geometryPixelShader": "#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include[3]\n#else\n#include[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}", "ssaoPixelShader": "\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}", "depthOfFieldPixelShader": "\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n", "standardPixelShader": "uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminanceshadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n", "fxaaVertexShader": "\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}", "fxaaPixelShader": "uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}", "sharpenPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}", "kernelBlurVertexShader": "\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}", "kernelBlurPixelShader": "\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include[0..varyingCount]\n#include[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}", "depthOfFieldMergePixelShader": "uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n", "circleOfConfusionPixelShader": "\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n", "bloomMergePixelShader": "uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n", "extractHighlightsPixelShader": "#include\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}", "refractionPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}", "blackAndWhitePixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}", "convolutionPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}", "filterPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}", "volumetricLightScatteringPixelShader": "uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i\n#include\n#include\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}", "lensFlareVertexShader": "\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}", "lensFlarePixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}", "anaglyphPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}", "stereoscopicInterlacePixelShader": "const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}", "vrDistortionCorrectionPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}", "glowBlurPostProcessPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}", "glowMapGenerationPixelShader": "#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}", "glowMapGenerationVertexShader": "\nattribute vec3 position;\n#include\n#include\n#include[0..maxSimultaneousMorphTargets]\n\n#include\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include[0..maxSimultaneousMorphTargets]\n#include\n#include\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}", "glowMapMergePixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}", "glowMapMergeVertexShader": "\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}", "lineVertexShader": "\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}", "linePixelShader": "uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}", "outlineVertexShader": "\nattribute vec3 position;\nattribute vec3 normal;\n#include\n\nuniform float offset;\n#include\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include\n}\n", "outlinePixelShader": "#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include\ngl_FragColor=color;\n}", "layerVertexShader": "\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}", "layerPixelShader": "\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}", "backgroundVertexShader": "precision highp float;\n#include<__decl__backgroundVertex>\n#include\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include\n\n#include\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include\n#include\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include\n#include\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include\n\n#include\n\n#include[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n", "backgroundPixelShader": "#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include\n#include\n#include\n#include\n#include\n\n#include\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n", "noisePixelShader": "\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif", "instancesDeclaration": "#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif", "pointCloudVertexDeclaration": "#ifdef POINTSIZE\nuniform float pointSize;\n#endif", "bumpVertexDeclaration": "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n", "clipPlaneVertexDeclaration": "#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif", "fogVertexDeclaration": "#ifdef FOG\nvarying vec3 vFogDistance;\n#endif", "morphTargetsVertexGlobalDeclaration": "#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif", "morphTargetsVertexDeclaration": "#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif", "logDepthDeclaration": "#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif", "morphTargetsVertex": "#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif", "instancesVertex": "#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif", "bonesVertex": "#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif", "bumpVertex": "#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif", "clipPlaneVertex": "#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif", "fogVertex": "#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif", "shadowsVertex": "#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif", "pointCloudVertex": "#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif", "logDepthVertex": "#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif", "helperFunctions": "const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}", "lightFragmentDeclaration": "#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif", "lightsFragmentFunctions": "\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}", "lightUboDeclaration": "#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif", "defaultVertexDeclaration": "\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n", "defaultFragmentDeclaration": "uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif", "defaultUboDeclaration": "layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};", "shadowsFragmentFunctions": "#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; icurrRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif", "clipPlaneFragmentDeclaration": "#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif", "fogFragmentDeclaration": "#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif", "clipPlaneFragment": "#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif", "bumpFragment": "vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif", "lightFragment": "#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif", "logDepthFragment": "#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif", "fogFragment": "#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif", "pbrVertexDeclaration": "uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n", "pbrFragmentDeclaration": "uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif", "pbrUboDeclaration": "layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};", "pbrFunctions": "\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}", "harmonicsFunctions": "#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif", "pbrLightFunctions": "\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}", "clipPlaneVertexDeclaration2": "#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif", "clipPlaneFragmentDeclaration2": "#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif", "mrtFragmentDeclaration": "#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n", "bones300Declaration": "#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif", "instances300Declaration": "#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif", "kernelBlurFragment": "#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif", "kernelBlurFragment2": "#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif", "kernelBlurVaryingDeclaration": "varying vec2 sampleCoord{X};", "kernelBlurVertex": "sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};", "backgroundVertexDeclaration": "uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif", "backgroundFragmentDeclaration": " uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif", "backgroundUboDeclaration": "layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};" };
var consent = void 0;
var ready_startup = false;
var ready_auth = false;
var ready_paperDoll = false;
var timerPlayStart = "";
var shadowGen;
var camera;
var gameStartTime;
var settings = {};
var optimizer;
var lastVer;
var adBlocker = false;
var inGame = false;
var paperDoll = null;
var servicesToken = null;
var playOffline = false;
var inputToControlMap = {};
var stampTexture;
var observingGame = false;
var watchPlayer = null;
var gameType;
var privateGame;
var gameCode;
var mapIdx;
var mapTest = {};
var freezeFrame = false;
var noSkybox = false;
var testing = false;
var timesPlayed;
var firebaseUi = null;
var anonymousUser = null;
var firebaseUser = null;
var signingIn = false;
var upgradingAnon = false;
var isRunning = false;
var debugArray = [];
var debugObject = {};
var pingTotal;
var pingSamples;
var nextPingSample;
var highestPing = 0;
var fpsTotal;
var fpsSamples;
var fpsAverage;
var linkItemShown = false;
var showTaggedItems = null;
var showNugget = null;
var adTest = false;
var aipPrerollPlayer;
var houseAds = [];
var houseAdsLoaded = false;
var chatInEl;
var chatOutEl;
var killEl;
var nameTestCanvas = document.createElement("canvas");
var joinType;
var isPrivateGame;
var joinedAs;
var autoInvite = false;
var isGameOwner;
var viewingPlayerId;
var myTeam;
var gamePaused = true;
var browserLanguage = navigator.language;
var userSetLanguage;
var adTagDebug = parsedUrl.query.debug;
var selectedSku = null;
var firebaseSignInTimerStart;
var loginProviderId = null;
var hasAccount = true;
var creatingAccount = false;
var pwaReady = false;
var pwaDeferredPrompt = "";
var shellProducts = null;
var adBlockerVideoTimer = 1e4;
var tryMidMonthRewardAgain = false;
var signinClicked = false;
var chicknWinner = null;
var shloopyBloopers = 5831;
var hasPlayBeenPressed = false;
var newGameStart = true;
var joinGameAttempted = false;
var openShopOnly = false;
var clientId = null;
var PhotoBooth;
var tutorialShowing = false;
var gameOptions;
var SessionStats;
var canvasWrapper;
var firstGamePlayed = false;
var showResendEmailPopup = false;
var AIPVideoAds = null;
var hasTimesPlayed = false;
var socialRewardClick = {
discord: 0,
ticTok: 0
};
var PremMeshNames = {};
var urlRewardParams = ["midMonthGiveMeEggs", "newYolkerSignupReward", "newYolkerItemReward", "newYolkerWelcomeBack", "WelcomeBack", "mercZoneFinalGift"];
var premFeatTag = { premFeatOne: 0, premFeatTwo: 0 };
var teamColors = {
text: ["rgba(254,216,56,1)", "rgba(64, 224, 255, 1)", "rgba(255, 192, 160, 1)"],
meBackground: ["rgba(255, 192, 64, 0.75)", "rgba(0, 192, 255, 0.8)", "rgba(192, 64, 32, 0.8)"],
themBackground: ["rgba(0, 0, 0, 0.25)", "rgba(0, 64, 192, 0.3)", "rgba(192, 64, 32, 0.3)"],
summaryBackground: ["rgba(64, 64, 64, 0.75)", "rgba(0, 64, 192, 0.75)", "rgba(192, 64, 32, 0.75)"],
outline: [
new BABYLON.Color4(1, 1, 1, 0),
new BABYLON.Color4(0, 0.75, 1, 1),
new BABYLON.Color4(1, 0.25, 0.25, 1)
],
textColor: [
new BABYLON.Color4(1, 1, 1, 1),
new BABYLON.Color4(0, 0.75, 1, 1),
new BABYLON.Color4(1, 0.25, 0.25, 1)
],
meClass: ["playerSlot-me", "playerSlot-me-blue", "playerSlot-me-red"],
themClass: ["playerSlot-them", "playerSlot-them-blue", "playerSlot-them-red"]
};
var ItemSearchSettings = {
isCaseSensitive: false,
includeScore: true,
shouldSort: true,
includeMatches: true,
findAllMatches: false,
minMatchCharLength: 1,
location: 0,
threshold: 0.2,
distance: 100,
useExtendedSearch: true,
// ignoreLocation: false,
// ignoreFieldNorm: false,
// fieldNormWeight: 1,
keys: [
"name",
"unlock",
"item_data.tags",
"item_data.meshName"
]
};
var adsLoaded = false;
var changelogData = [
{
"version": "0.47.4",
"date": "March 15 2024",
"content": [
"It's an Easter Miracle! New Default hats and stamps added for all players!",
"New players now are auto-equipped with random default items",
"The Easter skins are back in the shop with some sweet additions",
"Unwrap the Chocolate Eggk-47, the most delicious Premium item yet, in-store or free for VIPs",
"Moved Quarry, Feedlot, Bastion, Moonbase & Exposure to the public map pool",
"Moved Enchanted, Catacombs, Road, Backstage & Mud Gulch to the private map pool"
]
}
];
var version = changelogData[0].version;
var SsProducts = [
{ itemIds: null, sku: "egg_pack_small", name: "Small Pack", price: 3, salePrice: 5, flagText: "", type: "currency", inStore: 1, currency: 3e4, isActive: true },
{ itemIds: null, sku: "egg_pack_medium", name: "Medium Pack", price: 6, salePrice: 10, flagText: "", type: "currency", inStore: 1, currency: 65e3, isActive: true },
{ itemIds: null, sku: "egg_pack_large", name: "Large Pack", price: 12, salePrice: 20, flagText: "", type: "currency", inStore: 1, currency: 15e4, isActive: true },
{ itemIds: null, sku: "egg_pack_giant", name: "Giant Pack", price: 50, salePrice: 25, flagText: "p_egg_shop_bestvalue", type: "currency", inStore: 0, currency: 5e4, isActive: true },
{ itemIds: null, sku: "golden_chicken_pass", name: "Golden Chicken Pass", price: null, salePrice: null, flagText: "", type: "pass", inStore: 0, currency: 0, isActive: false },
{ itemIds: null, sku: "chicken_nugget_pass", name: "Chicken Nugget Pass", price: null, salePrice: null, flagText: "", type: "pass", inStore: 0, currency: 0, isActive: false },
{ itemIds: null, sku: "test_nugget_pass", name: "Test Nugget", price: null, salePrice: null, flagText: "", type: "pass", inStore: 0, currency: 0, isActive: false },
{ itemIds: [4223], sku: "item_gun_m24_techno", name: "Untz Untz Gun", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1112], sku: "item_hat_yolk_arms", name: "Yolk Arms", price: 1, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1105], sku: "item_hat_cape", name: "Magic Cape", price: 1, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1092], sku: "item_hat_dragon", name: "GoE Dragon", price: 2, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1110], sku: "item_hat_space_gladi", name: "Space Gladiator", price: 2, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1126], sku: "item_hat_zombie_mask", name: "Zombie Mask", price: 2, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3016], sku: "item_gun_9mm_space", name: "Cluck 9mm Space Egg", price: 4, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1125], sku: "item_hat_oni", name: "Oni Hat", price: 4, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3416], sku: "item_gun_csg1_space", name: "CSG1 Space Egg Skin", price: 3, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1160], sku: "item_hat_galeggsy", name: "Galeggsy Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3025], sku: "item_gun_9mm_techno", name: "Cluck 9mm Techno", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1171], sku: "item_hat_rooter_wing", name: "Rooster Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4026], sku: "item_gun_smg_techno", name: "Tuh SMG", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1174], sku: "item_hat_demon_wings", name: "Demon Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3627], sku: "gun_gauge_techno", name: "Badoosh Dozen Gauge", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1184], sku: "item_hat_fallen_wing", name: "Fallen Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3426], sku: "item_gun_csg1_techno", name: "CSG1 Techno Catz", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1185, 2204, 16011], sku: "1oOnkjL7", name: "1 month membership", price: 699, salePrice: null, flagText: "", type: "subscription", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1185, 2204, 16011], sku: "K5JjxL1z", name: "3 month membership", price: 1499, salePrice: null, flagText: "", type: "subscription", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1185, 2204, 16011], sku: "TymKKdoQ", name: "12 month membership", price: 4999, salePrice: null, flagText: "p_egg_shop_bestvalue", type: "subscription", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1185, 2204, 16011], sku: "item_hat_golden_wing", name: "Golden Wings", price: null, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1186], sku: "item_hat_chrome_wing", name: "Chrome Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3126], sku: "gun_eggk47_techno", name: "Eggk Poggers", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1193], sku: "item_hat_steamWings", name: "Steampunk Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3828], sku: "item_gun_rpeggTechno", name: "RPEGGTechno", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3029], sku: "item_gun_retro_9mm", name: "Retro Skin Cluck9mm", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1195], sku: "item_hat_pixel_wings", name: "Angel Pixel Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16014], sku: "item_gre_skullnado", name: "Skullnado", price: 7, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1202], sku: "item_hat_skull_wings", name: "Skull Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4512], sku: "item_gun_aug_retro", name: "Retro TriHard", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1215], sku: "item_hat_robot_wings", name: "Robot Pixel Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16019], sku: "item_gre_unicorn", name: "Unicorn Grenade", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1222], sku: "item_hat_uni_wing", name: "Unicorn Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [4229], sku: "item_gun_m24_retro", name: "M2DZ Retro Skin", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1226], sku: "item_hat_fairy_wings", name: "Fairy Pixel Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16023], sku: "item_gre_toilet_papr", name: "Grenade Toilet Paper", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1232], sku: "item_hat_toilet_papr", name: "Hat Toilet Paper", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3431], sku: "item_gun_csg1_retro", name: "CSG1 Retro", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1235], sku: "item_hat_pixel_fire", name: "Fire Pixel Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16027], sku: "item_gre_glitterbomb", name: "Grenade Glitterbomb", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1241], sku: "item_hat_glitch_wing", name: "Glitch Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3634], sku: "item_gun_crack_retro", name: "Scrambler Retro", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1245], sku: "item_hat_moth_wings", name: "Moth Pixel Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16032], sku: "item_gre_thermal", name: "Grenade Thermal Detonator", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1248], sku: "hat_thermal_wings", name: "Thermal Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4032], sku: "item_gun_smg_retro", name: "SMEGG Retro", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1269], sku: "item_hat_pixel_butt", name: "Pixel Butterfly Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1272], sku: "item_hat_pixel_bird", name: "Pixel Bird Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16036], sku: "item_gre_supernova", name: "Grenade Supernova", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16038], sku: "item_gre_octopus", name: "Grenade Octopus", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3835], sku: "item_gun_rpegg_retro", name: "RPEGG Retro", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1212], sku: "item_hat_dog_cap", name: "Dog Cap", price: 2, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1044], sku: "item_hat_egg_glasses", name: "Egg Glasses", price: 2, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1288], sku: "item_hat_luckywings", name: "Lucky Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1290], sku: "item_hat_ukraine", name: "Ukraine Bandana", price: 3, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3637], sku: "item_gun_bros", name: "Dozen Gauge Bros", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4528], sku: "item_gun_valk_aug", name: "Trihard Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16041], sku: "item_gre_diablo", name: "Grenade Diablo", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3134], sku: "item_gun_ak_retro", name: "Eggk47 Retro", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3136], sku: "item_gun_ak_valkyrie", name: "Eggk47 Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1312], sku: "item_hat_dinowings", name: "Dino Pterodactyl Win", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1316], sku: "item_hat_airplane", name: "Airplane Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1320], sku: "item_hat_crosswing", name: "Cross Fighter", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [16044], sku: "item_gre_bumble", name: "Grenade Bumblebee", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3642], sku: "item_gauge_valk", name: "Valkyrie Scrambler", price: 3, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16046], sku: "item_gre_football", name: "Grenade Football", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16048], sku: "item_gre_valk", name: "Grenade Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3439], sku: "item_csg1_rubchick", name: "CSG1 Rubber Chicken", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16049], sku: "item_gre_milk", name: "Grenade Milk", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4240], sku: "item_gun_m24_scav", name: "Crackshot Scavenger", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3045], sku: "item_gun_9mm_valk", name: "Cluck 9mm Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1341], sku: "item_hat_rainbow", name: "Rainbow Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3441], sku: "item_range_valk", name: "Free-Ranger Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1349], sku: "item_hat_teggtris", name: "Teggtris wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [16054], sku: "item_gre_blood", name: "Grenade Blood", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1356], sku: "item_hat_bloodwing", name: "Blood Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3843], sku: "item_gun_rpegg_valk", name: "RPEGG Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4040], sku: "item_gun_smg_turk", name: "Turkey-Supreme Whipp", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4242], sku: "item_gun_m24_valk", name: "Crackshot Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1363], sku: "item_hat_fall", name: "Fall Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3844], sku: "item_rpegg_christ", name: "RPEGG Santa Boot", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1369], sku: "item_holy_wings", name: "Holly Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [4042], sku: "item_gun_smg_valk", name: "Whipper Valkyrie", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1372, 3650], sku: "item_jan_2023", name: "Jan2023 Bundle", price: 10, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3443], sku: "item_csg1_fusion", name: "Free-Ranger Fusion", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1372], sku: "item_hat_soundwave", name: "Sound Wave Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3650], sku: "item_gauge_octopus", name: "Octopus Scrambler", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3050], sku: "item_9mm_cloud", name: "Cluck 9mm Clouds", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3142], sku: "item_ak47_fusion", name: "Eggk47 Fusion", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [16059], sku: "item_gre_pail", name: "Slop Bucket Grenade", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1389], sku: "item_hat_harp", name: "Harp Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [4044], sku: "item_smg_fusion", name: "Whipper Fusion", price: 3, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1394], sku: "item_hat_hooped", name: "Hooped", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3654], sku: "item_gauge_monster", name: "Beholder Scrambler", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1400], sku: "item_qwings", name: "Question Block Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3054], sku: "item_9mm_fusion", name: "Cluck 9mm Fusion", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [15023], sku: "item_melee_stone", name: "Stone Hammer Melee", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3445], sku: "item_csg1_shellpreme", name: "Free-Ranger Shellpre", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3655], sku: "item_gauge_fusion", name: "Fusion Scrambler", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3055], sku: "item_9mm_camera", name: "Cluck 9mm Camera", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1417], sku: "item_hat_surf", name: "Octopus Surfboard", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [15013], sku: "item_melee_valk", name: "Melee Valkyrie", price: 6, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [15030], sku: "item_melee_fusion", name: "The Fusion Melee", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1423], sku: "item_hat_scales", name: "Scales of Justice", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1225, 3420, 4208, 16013], sku: "bun_master_items", name: "Master items", price: 10, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [4540], sku: "item_aug_fusion", name: "Fusion Trihard", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1428], sku: "item_hat_glider", name: "Glider Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [16064], sku: "item_gre_timebomb", name: "Timebomb Grenade", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1349, 2157, 3029, 4039], sku: "bun_gamer", name: "Gamer Bundle", price: 8, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1185, 2204, 16011], sku: "kD7geYv2", name: "12 month membership", price: 4999, salePrice: null, flagText: "p_egg_shop_bestvalue", type: "subscription", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1185, 2204, 16011], sku: "gCLa2qqV", name: "1 month membership", price: 699, salePrice: null, flagText: "", type: "subscription", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1185, 2204, 16011], sku: "x0iYBjs4", name: "3 month membership", price: 1499, salePrice: null, flagText: "", type: "subscription", inStore: 0, currency: 0, isActive: false },
{ itemIds: [15037], sku: "item_melee_cat", name: "Harrison Cat Melee", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3059], sku: "item_9mm_mega", name: "Megaphone Cluck 9mm", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1118, 2242, 3060, 15040], sku: "bun_cat", name: "Cats Pajamas Bundle", price: 6, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1445], sku: "item_hat_wbs", name: "The Grand Entrance W", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [4248], sku: "item_m24_fusion", name: "The Fusion Crackshot", price: 6, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1450], sku: "item_hat_demonpixel", name: "Demon Pixel Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3951], sku: "item_rpegg_fusion", name: "Fusion RPEGG", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1031, 2454, 3035, 16054], sku: "bun_demon", name: "Demonic Bundle", price: 4, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3952], sku: "item_rpegg_skele", name: "Skellington RPEGG", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3149], sku: "item_ak_infernal", name: "Infernal Eggk47", price: 4, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1107, 2467, 15045, 16062], sku: "bun_mayan", name: "Mayan Bundle", price: 7, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1461], sku: "item_hat_mayan", name: "Ruins Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [15045], sku: "item_melee_mayan", name: "Mayan Macuahuitl", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1465], sku: "item_hat_breadcat", name: "Bread Cat", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [15047], sku: "item_melee_turkcar", name: "The Turkey Carver", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1465, 2372, 15025, 16022], sku: "bun_breadcat", name: "BreadCat Bundle", price: 7, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1470], sku: "item_hat_owl", name: "Snow Owl Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1263, 2229, 3844, 15049], sku: "bun_mistle", name: "Mistletoe Bundle", price: 9, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [4253], sku: "item_m24_infernal", name: "Infernal Crackshot", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1475], sku: "item_hat_disco", name: "Disco Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3455], sku: "item_csg1_infernal", name: "Infernal CSG1", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [1480], sku: "item_hat_racecar", name: "Racecar Wings", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [16071], sku: "item_gre_racecar", name: "Pireggi Grenade", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3455, 16071], sku: "bun_Jan24", name: "Jan Bundle", price: 10, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3662], sku: "item_gauge_cloud", name: "Cloudkicker Scramble", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1389, 2488, 4546, 16037], sku: "bun_cupid", name: "The Cupid Bundle", price: 6, salePrice: null, flagText: "", type: "bundle", inStore: 0, currency: 0, isActive: false },
{ itemIds: [16074], sku: "item_gre_fusion", name: "Fusion Grenade", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [15055], sku: "item_melee_worldcup", name: "World Cup Melee", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [3663], sku: "item_gauge_irish", name: "Irish Scrambler", price: 5, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: false },
{ itemIds: [1494, 2500, 3021, 16016], sku: "bun_badbunny", name: "Bad Bunny Bundle", price: 6, salePrice: null, flagText: "", type: "bundle", inStore: 1, currency: 0, isActive: true },
{ itemIds: [3058], sku: "item_9mm_infernal", name: "Infernal Cluck 9mm", price: 4, salePrice: null, flagText: "", type: "item", inStore: 0, currency: 0, isActive: true },
{ itemIds: [3154], sku: "item_ak_choc", name: "gun_eggk47_Chocolate", price: 5, salePrice: null, flagText: "", type: "item", inStore: 1, currency: 0, isActive: true }
];
var Items = [{ "id": 1001, "name": "Ball Cap", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_ballCap", "tags": ["Green", "White"] }, "is_available": true, "unlock": "default" }, { "id": 1002, "name": "Boat Fedora", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_boatHat", "tags": ["Blue", "Yellow"] }, "is_available": true, "unlock": "default" }, { "id": 1003, "name": "Top Hat", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_topHat", "tags": ["Black", "Grey", "Gray"] }, "is_available": true, "unlock": "default" }, { "id": 1004, "name": "Derby Hat", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_derby", "tags": ["Orange", "Brown"] }, "is_available": true, "unlock": "default" }, { "id": 1005, "name": "Mountie Hat", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mounty", "tags": ["Brown", "Police"] }, "is_available": true, "unlock": "default" }, { "id": 1006, "name": "Pablo Hat", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cowSheriff", "tags": ["Orange", "Brown", "Police", "Meme"] }, "is_available": true, "unlock": "default" }, { "id": 1007, "name": "Blue Bandana", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaBlue", "tags": ["Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1008, "name": "Hero Mask", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_batman", "tags": ["Black", "Brown", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1009, "name": "Cop Hat", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cop", "tags": ["Blue", "Gold", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1010, "name": "Robber Mask", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_badEgg2", "tags": ["Black", "Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 1011, "name": "Red Bandana", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaRed", "tags": ["Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 1012, "name": "Pink Bow", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bowPink", "tags": ["Pink"] }, "is_available": true, "unlock": "purchase" }, { "id": 1013, "name": "Glasses", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_glasses", "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1014, "name": "Pompadour", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pompadour", "tags": ["Black", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1015, "name": "Plague Doctor Mask", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_plagueDoctor", "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1016, "name": "Poop Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_poop", "tags": ["Brown", "Yellow", "Gold", "Poop"] }, "is_available": true, "unlock": "purchase" }, { "id": 1017, "name": "Unicorn Hat", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_unicorn", "tags": ["Red", "Orange", "Yellow", "Green", "Blue", "Silver", "Rainbow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1018, "name": "Baws Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pimp", "tags": ["Black", "White", "Grey", "Gray", "Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 1019, "name": "Pirate Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pirateHat", "tags": ["Black", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 1023, "name": "Hunting Hat", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_hunting", "tags": ["Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 1024, "name": "Hunting Bear Hat", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_huntingBear", "tags": ["Pink", "Heart", "Cute"] }, "is_available": true, "unlock": "purchase" }, { "id": 1025, "name": "Crown", "price": 2e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_crown", "tags": ["Gold", "Red", "Royal"] }, "is_available": true, "unlock": "purchase" }, { "id": 1020, "name": "ShellShockers Hat", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_shellshockers", "unlock": "physical", "physicalUnlockLocKey": "p_physical_unlock_hat", "physicalItemStoreURL": "https://shell-shockers.myshopify.com/products/splat-hat", "tags": ["White", "Brown", "Egg"] }, "is_available": false, "unlock": "physical" }, { "id": 1021, "name": "Frying Pan", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fryingPan", "unlock": "physical", "physicalUnlockLocKey": "p_physical_unlock_pan", "physicalItemStoreURL": "https://shell-shockers.myshopify.com/products/no-pans-tee", "tags": ["Black", "Silver"] }, "is_available": false, "unlock": "physical" }, { "id": 1022, "name": "Viking Horns", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_horns", "unlock": "physical", "physicalUnlockLocKey": "p_physical_unlock_shirt", "physicalItemStoreURL": "https://shell-shockers.myshopify.com/products/logo-tee", "tags": ["Brown", "Bone"] }, "is_available": false, "unlock": "physical" }, { "id": 1026, "name": "Jack O' Lantern Hat", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pumpkin", "tags": ["Halloween", "Oct23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 1027, "name": "Bat Wings", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_batWings", "tags": ["Halloween", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1028, "name": "Witch Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_witch", "tags": ["Halloween", "Purple", "Gold", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1029, "name": "Axe-in-head", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_axe", "tags": ["Halloween", "Oct23", "Red", "Brown", "Wood"] }, "is_available": false, "unlock": "purchase" }, { "id": 1030, "name": "Executioner's Cowl", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_executioner", "tags": ["Halloween", "Oct23", "Red", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1031, "name": "Devil Horns", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_devilHorns", "tags": ["Halloween", "Oct23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1032, "name": "Angel Wings & Halo", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_angel", "tags": ["Halloween", "Oct23", "Gold", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1033, "name": "Hockey Mask", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_hockeyMask", "tags": ["Halloween", "Oct23", "Black", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1034, "name": "Pilgrim Hat", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pilgrim", "tags": ["NovM23", "Thanksgiving", "Black", "Brown", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 1035, "name": "Cooked Turkey Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_turkeyDead", "tags": ["NovM23", "Thanksgiving", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1036, "name": "Turkey Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_turkeyAlive", "tags": ["NovM23", "Thanksgiving", "Brown", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1037, "name": "Golden Chicken Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_Top1Percent", "tags": ["Reward", "RewardTopPercent", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1038, "name": "Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KillTier1", "tags": ["Reward", "RewardKills", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1039, "name": "Bronze Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KillTier2", "tags": ["Reward", "RewardKills", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1040, "name": "Silver Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KillTier3", "tags": ["Reward", "RewardKills", "Gray", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1041, "name": "Gold Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KillTier4", "tags": ["Reward", "RewardKills", "Gold", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 1042, "name": "Cracked Egg Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_DeathTier1", "tags": ["Reward", "RewardDeaths", "Yellow", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1043, "name": "Egg Headphones", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_DeathTier2", "tags": ["Reward", "RewardDeaths", "Yellow", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1044, "name": "Egg Glasses", "price": 2, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_DeathTier3", "tags": ["Reward", "RewardDeaths", "Yellow", "White"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_egg_glasses"] }, { "id": 1045, "name": "Cracked Egg Crown", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_DeathTier4", "tags": ["Reward", "RewardDeaths", "Yellow", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1046, "name": "Chicken Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KDRTier1", "tags": ["Reward", "RewardKDR", "Bone"] }, "is_available": false, "unlock": "manual" }, { "id": 1047, "name": "Bronze Chicken Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KDRTier2", "tags": ["Reward", "RewardKDR", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1048, "name": "Silver Chicken Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KDRTier3", "tags": ["Reward", "RewardKDR", "Silver", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1049, "name": "Gold Chicken Skull Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_KDRTier4", "tags": ["Reward", "RewardKDR", "Yellow", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1050, "name": "Golden Egg Trophy", "price": 100, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_GoldenEggTier1", "tags": ["Eggflation", "MayM23", "Gold"] }, "is_available": true, "unlock": "purchase" }, { "id": 1051, "name": "Golden Faberge Egg Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_GoldenEggTier2", "tags": ["Eggflation", "MayM23", "Gold"] }, "is_available": true, "unlock": "purchase" }, { "id": 1052, "name": "Dollar Sign Glasses", "price": 1e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_GoldenEggTier3", "tags": ["Eggflation", "MayM23", "Gold"] }, "is_available": true, "unlock": "purchase" }, { "id": 1053, "name": "Golden Baws Hat", "price": 1e5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_GoldenEggTier4", "tags": ["Eggflation", "MayM23", "Gold"] }, "is_available": true, "unlock": "purchase" }, { "id": 1054, "name": "Nate's Headphones", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_headphones", "tags": ["Nate", "Green", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1055, "name": "Reindeer Antlers", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_reindeer", "tags": ["Dec23", "Christmas", "Green", "Red", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1056, "name": "Elf Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_elf", "tags": ["Dec23", "Christmas", "Green", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 1057, "name": "Santa Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_santa", "tags": ["Dec23", "Christmas", "White", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1058, "name": "Party Hat 2019", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_party", "tags": ["NewYears", "2019", "Black", "Gold", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1059, "name": "Headband 2019", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_2019", "tags": ["NewYears", "2019", "Black", "Gold", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1060, "name": "Happy New Yolk Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_newYolk", "tags": ["NewYears", "Black", "Gold", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1061, "name": "Ski Mask", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_badEgg1", "tags": ["Newsletter", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1062, "name": "Pirate Bandana", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaPirate", "tags": ["Newsletter", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1063, "name": "Colander Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_colander", "tags": ["Newsletter", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1064, "name": "Hamburger Earmuffs", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_earmuffsHamburger", "tags": ["Newsletter", "Brown", "Pickles"] }, "is_available": false, "unlock": "manual" }, { "id": 1065, "name": "Fez Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fez", "tags": ["Newsletter", "Red", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1066, "name": "Blue Wizard Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_blueWizard", "tags": ["Newsletter", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1067, "name": "Chef Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_chef", "tags": ["Newsletter", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1068, "name": "Jester Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_jester", "tags": ["Newsletter", "Black", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1069, "name": "Straw Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_straw", "tags": ["Newsletter", "Blue", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1070, "name": "Spring Sapling Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spring", "tags": ["Groundhog", "Feb23", "Green", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 1071, "name": "Winter Sapling Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_winter", "tags": ["Groundhog", "Feb23", "White", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 1072, "name": "Groundhog Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 1073, "name": "Skull Bandana", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaSkull", "tags": ["Promotional", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1074, "name": "Firefighter Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fireFighter", "tags": ["Promotional", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1075, "name": "Sunglasses", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sunglasses", "tags": ["Promotional", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1076, "name": "Monocle", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_monocle", "tags": ["Newsletter", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1077, "name": "Gas Mask", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gasMask", "tags": ["Promotional", "Black", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1078, "name": "Aviator Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_aviator", "tags": ["Promotional", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1079, "name": "Red Goggles", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gogglesRed", "tags": ["Promotional", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1080, "name": "Astronaut Helmet", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_astronaut", "tags": ["Promotional", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1081, "name": "Heart Glasses", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_glassesHeart", "tags": ["ValentinesDay", "Pink", "Red", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 1082, "name": "Baws Fedora", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fedoraPimp", "tags": ["ValentinesDay", "Pink", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1083, "name": "Valentine's Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_valentines", "tags": ["ValentinesDay", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1084, "name": "Shamrock Glasses", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_glassesShamrock", "tags": ["StPatricksDay", "MarM23", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1085, "name": "Pot O' Gold Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_potOfGold", "tags": ["StPatricksDay", "MarM23", "Black", "Gold", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1086, "name": "Leprechaun Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_leprechaun", "tags": ["StPatricksDay", "MarM23", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1087, "name": "Bunny Ears", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bunnyEars", "tags": ["Easter", "White", "Pink", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1088, "name": "Egg Nest", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggNest", "tags": ["Easter", "Brown", "Grey", "Gray", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1089, "name": "Egg Basket", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggBasket", "tags": ["Easter", "Brown", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1090, "name": "Egg Crown", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggCrown", "tags": ["Easter", "Blue", "Yellow", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1091, "name": "GoE Ice Crown", "price": 15e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_iceCrown", "tags": ["GameOfEggs", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1092, "name": "GoE Dragon", "price": 2, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dragon", "tags": ["GameOfEggs", "May23", "Green"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_dragon"] }, { "id": 1093, "name": "Green Bandana", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaGreen", "tags": ["Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 1094, "name": "Mohawk Hair", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_moHawk", "tags": ["Purple", "Pink"] }, "is_available": true, "unlock": "purchase" }, { "id": 1095, "name": "Bihawk Hair", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_biHawk", "tags": ["Green", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1096, "name": "Trihawk Hair", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_triHawk", "tags": ["Red", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1097, "name": "Pigtails Hair", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pigtails", "tags": ["Yellow", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1098, "name": "Side Pony", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sidePony", "tags": ["Black", "Pink", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1099, "name": "Egg Helmet", "price": 1e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggHelmet", "tags": ["Aveggers", "Gold", "Bone"] }, "is_available": false, "unlock": "purchase" }, { "id": 1100, "name": "Fohawk Wig", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_arrow", "tags": ["Aveggers", "Brown", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1101, "name": "American Bandana", "price": 2e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaAmerica", "tags": ["Aveggers", "JulyM23", "Red", "White", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1102, "name": "Bike Helmet", "price": 25e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bikeHelmet", "tags": ["Aveggers", "Red", "Yellow", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1103, "name": "Bucket Hero Hat", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bucketMan", "tags": ["Aveggers", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1104, "name": "Bug Mask", "price": 25e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bugMask", "tags": ["Aveggers", "Jun23", "Red", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1105, "name": "Magic Cape", "price": 1, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cape", "tags": ["Aveggers", "Jun23", "Red", "Purple", "Pink"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_cape"] }, { "id": 1106, "name": "Eyepatch", "price": 15e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eyepatch", "tags": ["Aveggers", "May23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1107, "name": "Panther Mask", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pantherMask", "tags": ["Aveggers", "Black", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1108, "name": "Red Hair Wig", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_redHair", "tags": ["Aveggers", "Black", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1109, "name": "Helmet of Sight", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sightHelmet", "tags": ["Aveggers", "Purple", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1110, "name": "Space Gladiator Hat", "price": 2, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spaceGladiator", "tags": ["Aveggers", "JunM23", "Red", "Brown"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_space_gladi"] }, { "id": 1111, "name": "Spider Mask", "price": 12e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spiderMask", "tags": ["Aveggers", "Sep23", "Red", "Black", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1112, "name": "Yolk Arms Hat", "price": 1, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_yolkArms", "tags": ["Aveggers", "Mar23", "Yellow", "MarM24", "premFeatTwo"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_yolk_arms"] }, { "id": 1113, "name": "Guy Fawkes Mask", "price": 1105, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fawkes", "tags": ["Bone"] }, "is_available": true, "unlock": "purchase" }, { "id": 1114, "name": "Birthday Hat 1", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_birthday1", "tags": ["HappyBirthday", "Yellow", "Red", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1115, "name": "Birthday Hat 2", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_birthday2", "tags": ["HappyBirthday", "Red", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1116, "name": "Birthday Cake Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cake", "tags": ["HappyBirthday", "Red", "Blue", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1117, "name": "League Staff Sash", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_leagueStaff", "tags": ["League", "Blue", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 1118, "name": "Cat Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cat", "tags": ["Orange", "Black", "Cat"] }, "is_available": true, "unlock": "purchase" }, { "id": 1119, "name": "Egg Shell Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggshell", "tags": ["Bone"] }, "is_available": true, "unlock": "purchase" }, { "id": 1120, "name": "Dino Shell Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dinoShell", "tags": ["Orange", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1121, "name": "Penguin Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_penguin", "tags": ["Black", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 1122, "name": "Pot Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pot", "tags": ["Black", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 1123, "name": "Tiny Tophat", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_tophatTiny", "tags": ["Black", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 1124, "name": "Nurse Hat", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_nurse", "tags": ["White", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 1125, "name": "Oni Hat", "price": 4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_oni", "tags": ["Sidearms", "White", "Red", "Black", "MarM24", "premFeatTwo"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_oni"] }, { "id": 1126, "name": "Zombie Mask", "price": 2, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_zombieMask", "tags": ["July23", "Black"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_zombie_mask"] }, { "id": 1127, "name": "Cinnamon Bun Hair", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cinnamonBun", "tags": ["Eggwalker", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1128, "name": "Bounty Egger", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bountyEgger", "tags": ["Eggwalker", "Green", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1129, "name": "Good Robes Hat", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_goodRobes", "tags": ["Eggwalker", "Brown", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1130, "name": "Bad Robes Hat", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_badRobes", "tags": ["Eggwalker", "Black", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1131, "name": "Space Emo Hair", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spaceEmo", "tags": ["Eggwalker", "Black", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1132, "name": "Space Monk Cloak", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spaceMonk", "tags": ["Eggwalker", "Blue", "Bone"] }, "is_available": false, "unlock": "purchase" }, { "id": 1133, "name": "Eggperor Hat", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggperor", "tags": ["Eggwalker", "Black", "Yellow", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1134, "name": "BBEgg Hat", "price": 65e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bbEgg", "tags": ["Eggwalker", "Orange", "White", "MarM24", "premFeatTwo"] }, "is_available": true, "unlock": "purchase" }, { "id": 1135, "name": "C3PYolk Mask", "price": 1e5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_c3pYolk", "tags": ["Eggwalker", "Rainbow", "Gold", "premFeatOne", "Mar24"] }, "is_available": false, "unlock": "purchase" }, { "id": 1136, "name": "2020 Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_2020", "tags": ["NewYears", "2020", "Yellow", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1137, "name": "Eggy Cash Ensemble", "price": 75e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggyCash", "tags": ["EggyCash", "Brown", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1138, "name": "Soda Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_drinkdew", "tags": ["Newsletter", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1139, "name": "Surgical Mask", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_surgicalMask", "tags": ["Surgical", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 1140, "name": "Surgical Mask White", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_surgicalWhite", "tags": ["Surgical", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 1141, "name": "Surgical Mask Smile", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_surgicalSmile", "tags": ["Surgical", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1142, "name": "Falcon Hunter Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_falconHunter", "tags": ["RaidLand", "Yellow", "Nov23"] }, "is_available": false, "unlock": "purchase" }, { "id": 1143, "name": "Shadow Hunter Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_shadowHunter", "tags": ["RaidLand", "Mar23", "Purple"] }, "is_available": false, "unlock": "purchase" }, { "id": 1144, "name": "Frost Berserker Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_frostBerserker", "tags": ["RaidLand", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1145, "name": "Grim Berserker Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_grimBerserker", "tags": ["RaidLand", "Blue", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 1146, "name": "Golem Warrior Hat", "price": 1200, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_golemWarrior", "tags": ["RaidLand", "Green", "premFeatOne", "Mar24"] }, "is_available": false, "unlock": "purchase" }, { "id": 1147, "name": "Immortal Warrior Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_immortalWarrior", "tags": ["RaidLand", "Blue", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 1148, "name": "Sheep Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sheep", "tags": ["Newsletter", "White", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1149, "name": "Blue Toxic Bandana", "price": 7500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toxicBlue", "tags": ["Rotten", "Blue", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 1150, "name": "Green Toxic Bandana", "price": 7500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toxicGreen", "tags": ["Rotten", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 1151, "name": "Orange Toxic Bandana", "price": 7500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toxicOrange", "tags": ["Rotten", "Orange", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 1152, "name": "Double Filter Gas Mask", "price": 75e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_doubleFilter", "tags": ["Black", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 1153, "name": "Brown Rockstar Hair", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_rockstar1", "tags": ["Rockstar", "JanM23", "Brown", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 1154, "name": "Black & Red Rockstar Hair", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_rockstar3", "tags": ["Rockstar", "JanM23", "Black", "Red", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 1155, "name": "Black & White Rockstar Hair", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_rockstar2", "tags": ["Rockstar", "JanM23", "Black", "White", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 1156, "name": "Umbrella Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_umbrella", "tags": ["Newsletter", "Rainbow"] }, "is_available": false, "unlock": "manual" }, { "id": 1157, "name": "Star Glasses", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_glassesStar", "tags": ["Galeggsy", "AprM23", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 1158, "name": "Star Bandana", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaStars", "tags": ["Galeggsy", "AprM23", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 1159, "name": "Alien Antennae", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_headbandAlien", "tags": ["Galeggsy", "AprM23", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 1160, "name": "Galeggsy Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premiumButterfly", "tags": ["Galeggsy", "AprM23", "Purple", "Pink"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_galeggsy"] }, { "id": 1161, "name": "Black Suit Ensemble", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mercZoneBlack", "tags": ["MercZone", "Black", "Suit"] }, "is_available": false, "unlock": "manual" }, { "id": 1162, "name": "Red Suit Ensemble", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mercZoneRed", "tags": ["MercZone", "Red", "Suit"] }, "is_available": false, "unlock": "manual" }, { "id": 1163, "name": "Pink Suit Ensemble", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mercZonePink", "tags": ["MercZone", "Pink", "Suit"] }, "is_available": false, "unlock": "manual" }, { "id": 1164, "name": "Academic Cap", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_academic", "tags": ["Newsletter", "Black", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 1166, "name": "Fuzzy Earmuffs", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_earmuffs", "tags": ["Newsletter", "Pink"] }, "is_available": false, "unlock": "manual" }, { "id": 1167, "name": "Chains Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_chains", "tags": ["Newsletter", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1168, "name": "Hen Hat", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_hen", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1169, "name": "Rooster Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_rooster", "tags": ["Chicken", "Brown", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1170, "name": "Rooster Tail Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_roosterTail", "tags": ["Chicken", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1171, "name": "Rooster Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_RoosterWings", "tags": ["MayM23", "Chicken", "Green", "Red"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_rooter_wing"] }, { "id": 1172, "name": "Bee Wings", "price": 1e5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_BeeWings", "tags": ["Rainbow", "Pink", "Green", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1173, "name": "Jason Mask", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_F13", "tags": ["f13", "Bone", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1174, "name": "Demon Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_DemonWings", "tags": ["Premium", "Red", "OctM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_demon_wings"] }, { "id": 1175, "name": "Among Egg Hat 1", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_amongEgg_01", "tags": ["AmongEgg", "Blue", "White", "Meme"] }, "is_available": true, "unlock": "purchase" }, { "id": 1176, "name": "Among Egg Hat 2", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_amongEgg_02", "tags": ["AmongEgg", "Blue", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1177, "name": "Among Egg Hat 3", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_amongEgg_03", "tags": ["AmongEgg", "Blue", "Brown", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1178, "name": "Among Egg Hat 4", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_amongEgg_04", "tags": ["AmongEgg", "Blue", "Brown", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1179, "name": "Among Egg Hat 5", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_amongEgg_05", "tags": ["AmongEgg", "Blue", "Brown", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1180, "name": "Among Egg Hat 6", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_amongEgg_06", "tags": ["AmongEgg", "Blue", "Brown", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1181, "name": "Among Egg Hat 7", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_amongEgg_07", "tags": ["AmongEgg", "Blue", "Brown", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1182, "name": "Eggolorian Helmet", "price": 75e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggolorianBig", "tags": ["Eggolorian", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1183, "name": "Toadstool Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toadstool", "tags": ["Newsletter", "Red", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1184, "name": "Fallen Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_FallenWings", "tags": ["Premium", "FebM23", "Gray", "Brown"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_fallen_wing"] }, { "id": 1185, "name": "Golden Wings", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_GoldenWings", "tags": ["Premium", "vipItem", "Gray", "Silver"] }, "is_available": false, "unlock": "vip", "activeProduct": false, "sku": ["item_hat_golden_wing"] }, { "id": 1186, "name": "Chrome Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_ChromeWings", "tags": ["July23", "Gold", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_chrome_wing"] }, { "id": 1187, "name": "Wero Viking Hair", "price": 4e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_wero", "tags": ["Wero", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1188, "name": "Mech Energy Wings", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_MechEnergyWings", "tags": ["Newsletter", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1189, "name": "Egg Sandwich Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sandwich", "tags": ["Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1190, "name": "Party Hat 2021", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_party2021", "tags": ["NewYears", "2021", "Red", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1191, "name": "Headband 2021", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_2021", "tags": ["NewYears", "2021", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1192, "name": "Hindsight Glasses", "price": 24e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_glassesHindsight", "tags": ["NewYears", "Black", "Purple"] }, "is_available": false, "unlock": "purchase" }, { "id": 1193, "name": "Steampunk Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_SteampunkWings", "tags": ["Premium", "JulyM23", "Gold"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_steamWings"] }, { "id": 1194, "name": "Thee_Owl Hat", "price": 1e5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_theeowl", "tags": ["TheeOwl", "Red", "Orange", "Green", "Blue", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1195, "name": "Angel Pixel Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelAngel", "tags": ["Jun23", "Blue", "Yellow", "White"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_pixel_wings"] }, { "id": 1196, "name": "C4bra Hair", "price": 15e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_c4bra", "tags": ["C4bra", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1197, "name": "C4bra Ram Hat", "price": 35e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_c4brahorn", "tags": ["C4bra", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1198, "name": "Hazmatt Mask", "price": 5e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_hazmat", "tags": ["Hazmat", "Yellow", "Gold"] }, "is_available": true, "unlock": "purchase" }, { "id": 1199, "name": "Slashy Camp Mask", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_slashy", "tags": ["SlashyCamp", "White", "Bone", "Red", "Brown", "Skullface", "Slayaway"] }, "is_available": false, "unlock": "manual" }, { "id": 1200, "name": "Discord Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_discord", "tags": ["Discord", "Black", "Purple", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1201, "name": "Definitely not Egg", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_funnyGlasses", "tags": ["Newsletter", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1202, "name": "Skull Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_SkullWings", "tags": ["Red", "Brown", "Black", "Bone", "Oct23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_skull_wings"] }, { "id": 1203, "name": "Egg Earpods", "price": 25e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_airpods", "tags": ["White"] }, "is_available": true, "unlock": "purchase" }, { "id": 1204, "name": "Paper Bag Mask", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bag", "tags": ["Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1205, "name": "Backwards Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_hipster", "tags": ["Egg", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1206, "name": "Beret", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_beret", "tags": ["White", "Red", "Egg"] }, "is_available": true, "unlock": "purchase" }, { "id": 1207, "name": "Spike Hat", "price": 7500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spike", "tags": ["Gold", "Black", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1208, "name": "TikTok Bowler", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_tiktok", "tags": ["Pink", "Blue", "Black", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1209, "name": "Propeller Beanie", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_beanie", "tags": ["Newsletter", "Rainbow", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1210, "name": "Riddler Bowler", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_riddler", "tags": ["Purple", "Yellow", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1211, "name": "Miner Helmet", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_miner", "tags": ["Yellow", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1212, "name": "Dog Ears", "price": 2, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dog", "tags": ["sale", "Mar23", "Brown", "NovM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_dog_cap"] }, { "id": 1213, "name": "Satellite Headgear", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_satellite", "tags": ["Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 1214, "name": "Diablo Hat", "price": 100, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_evilpablo", "tags": ["EGGORG", "Black", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1215, "name": "Robot Pixel Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelRobot", "tags": ["Aug23", "Green", "Gray", "Black"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_robot_wings"] }, { "id": 1216, "name": "Train Conductor", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_conductor", "tags": ["Trains", "Cars", "Yellow", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1217, "name": "Train Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_train", "tags": ["Trains", "Cars", "Red", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 1218, "name": "Bindle Hat", "price": 4500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bindle", "tags": ["Trains", "Cars", "Red", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1219, "name": "Instagram Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_instagram", "tags": ["Purple", "Orange", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1220, "name": "UFO Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_ufo", "tags": ["Newsletter", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1221, "name": "RandomLife Headgear", "price": 5e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_randomlife", "tags": ["Random", "Red", "Brown", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1222, "name": "Unicorn Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_UnicornWings", "tags": ["Mar23", "Pink", "White"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_uni_wing"] }, { "id": 1223, "name": "Steam Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_steam", "tags": ["Pink"] }, "is_available": false, "unlock": "manual" }, { "id": 1224, "name": "Ice Cream Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_icecream", "tags": ["Newsletter", "Blue", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1225, "name": "Ethan Gamer Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_ethangamer", "tags": ["EthanGamer", "Brown", "Green", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1226, "name": "Fairy Pixel Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelFairy", "tags": ["Dec23", "Pink", "Blue"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_fairy_wings"] }, { "id": 1227, "name": "Facebook Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_facebook", "tags": ["Blue", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 1228, "name": "Sun Hat", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sun", "tags": ["Summer", "JunM23", "Yellow", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1229, "name": "Picnic Basket Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_picnic", "tags": ["Summer", "JunM23", "Brown", "White", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1230, "name": "Beehive Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_beehive", "tags": ["Summer", "JunM23", "Yellow", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1231, "name": "Parrot Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_parrot", "tags": ["Newsletter", "Red", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1232, "name": "Toilet Paper Wings", "price": 10, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_ToiletPaperWings", "tags": ["Premium", "White", "Brown"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_toilet_papr"] }, { "id": 1233, "name": "Watermelon Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_watermelon", "tags": ["Newsletter", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1234, "name": "Twitter Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_twitter", "tags": ["Blue", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1235, "name": "Fire Pixel Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelFire", "tags": ["Premium", "Red", "Yellow", "premFeatOne", "Mar24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_pixel_fire"] }, { "id": 1236, "name": "Backpack Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_backpack", "tags": ["Pencil", "Sep23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1237, "name": "Backpack Rainbow Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_backpackrainbow", "tags": ["Pencil", "Sep23", "Rainbow", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1238, "name": "Round Glasses", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_roundglasses", "tags": ["Pencil", "Sep23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1239, "name": "Books Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_books", "tags": ["Newsletter", "Yellow", "Brown", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1240, "name": "Wero Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_weroShort", "tags": ["Wero", "Brown", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1241, "name": "Glitch Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_GlitchWings", "tags": ["Premium", "Purple", "Pink", "Black", "NovM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_glitch_wing"] }, { "id": 1242, "name": "Sherlock Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sherlock", "tags": ["Newsletter", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1243, "name": "Grave Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_RIP", "tags": ["Halloween2", "Oct23", "Grey", "Gray", "Egg"] }, "is_available": false, "unlock": "purchase" }, { "id": 1244, "name": "Ghost Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_ghost", "tags": ["Halloween2", "Oct23", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1245, "name": "Moth Pixel Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelMoth", "tags": ["Nov23", "Brown", "Black", "Skull", "Lambs"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_moth_wings"] }, { "id": 1246, "name": "Android Hat", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_android", "tags": ["Mobile", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1247, "name": "Bravo Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bravo", "tags": ["Newsletter", "Yellow", "Hair"] }, "is_available": false, "unlock": "manual" }, { "id": 1248, "name": "Thermal Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_ThermalWings", "tags": ["Red", "DecM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["hat_thermal_wings"] }, { "id": 1249, "name": "Apple Pie Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_applepie", "tags": ["Food", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1250, "name": "Pumpkin Pie Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pumpkinpie", "tags": ["Food", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1251, "name": "Cheese Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cheese", "tags": ["Food", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1252, "name": "Gravy hat", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gravy", "tags": ["Food", "Brown", "Yellow", "NovM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 1253, "name": "Dollar Sign Glasses Black", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_PremiumEggTier3", "tags": ["Black Fryday", "MayM23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1254, "name": "Pink Hair", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pinkwarrior", "tags": ["Eggs of Legends", "Pink"] }, "is_available": true, "unlock": "purchase" }, { "id": 1255, "name": "Blue Braids", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bluebraids", "tags": ["Eggs of Legends", "Blue", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1256, "name": "Weather Vane", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_weathervane", "tags": ["KotC", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 1257, "name": "Red Crown Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_winnerRed", "tags": ["KotC", "Gold", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 1258, "name": "Blue Crown Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_winnerBlue", "tags": ["KotC", "Gold", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1259, "name": "Bison Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bison", "tags": ["Newsletter", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1260, "name": "Egg Cluster Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggcluster", "tags": ["KotC", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1261, "name": "Party Hat 2022", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_party2022", "tags": ["NewYears", "2022", "Brown", "Red", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1262, "name": "Headband 2022", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_2022", "tags": ["NewYears", "2022", "Red", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1263, "name": "Nervous Elf Belt", "price": 1e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_nervouself", "tags": ["Christmas2", "Elf", "Brown", "Gold", "Green", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1264, "name": "Bugs Hair", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bluehair", "tags": ["Meggtrix", "JulyM23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1265, "name": "Meggtrix Glasses", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_clampglasses", "tags": ["Meggtrix", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1266, "name": "Agent Smithe Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_smith", "tags": ["Meggtrix", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1267, "name": "Dreadlocks Hair", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_twins", "tags": ["Meggtrix", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 1268, "name": "Twitch Bits", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bits", "tags": ["Purple", "Green", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1269, "name": "Butterfly Pixel Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelButterfly", "tags": ["Purple", "Blurple"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_pixel_butt"] }, { "id": 1270, "name": "Mandrake Glasses", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mandrake", "tags": ["Drops", "Blue", "Black", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1271, "name": "Lyerpald Wolf Helmut", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_lyerpald", "tags": ["Drops", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1272, "name": "Pixel Bird Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelBird", "tags": ["Premium", "AugM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_pixel_bird"] }, { "id": 1273, "name": "xSerpius Hair", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_xserpiusbeard", "tags": ["Drops", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 1274, "name": "Blue & Yellow Toque ", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toque", "tags": ["Chilly", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1275, "name": "Purple & Red Toque", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pufftoque", "tags": ["Chilly", "Purple", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1276, "name": "Ear Flaps Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_greenearhat", "tags": ["Chilly", "Sep23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1277, "name": "Bow Headband", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pinkbow", "tags": ["Kawaii", "Blue", "Pink", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1278, "name": "Cute Ponytail", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pinkpony", "tags": ["Kawaii", "Pink", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1279, "name": "High Pigtails", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_hightails", "tags": ["Kawaii", "Purple", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1280, "name": "Orange Hair Buns", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spacebuns", "tags": ["Kawaii", "Orange"] }, "is_available": true, "unlock": "purchase" }, { "id": 1281, "name": "Cat Braids", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_catbraids", "tags": ["Kawaii", "Brown", "Hair"] }, "is_available": true, "unlock": "purchase" }, { "id": 1282, "name": "Sashimi Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sushi", "tags": ["Kawaii", "Pink", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 1283, "name": "Big Cat Ears", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bigears", "tags": ["Kawaii", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1284, "name": "Spiky Hair", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spikyband", "tags": ["Kawaii", "White", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1285, "name": "Gamer Hair", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gamerhair", "tags": ["Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 1286, "name": "Purple Hair", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_purplehair", "tags": ["Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 1287, "name": "Mmm Donut Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_donut", "tags": ["Newsletter", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1288, "name": "Lucky Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_LuckyWings", "tags": ["StPatricksDay", "MarM23", "Green", "premFeatOne", "Mar24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_luckywings"] }, { "id": 1289, "name": "Turtle Power Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_turtle", "tags": ["Newsletter", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1290, "name": "Ukraine Bandana", "price": 3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bandanaUkraine", "tags": ["UA", "Blue", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_ukraine"] }, { "id": 1291, "name": "Sweatband", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sweatband", "tags": ["Bros", "Egg", "Purple", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 1292, "name": "Spartan Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_spartan", "tags": ["Bros", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1293, "name": "Gators Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gators", "tags": ["Bros", "Blue", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 1294, "name": "Rams Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_rams", "tags": ["Bros", "Aug23", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1295, "name": "Knight Hat", "price": 1520, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_knight", "tags": ["EGGORG", "Blue", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1296, "name": "Viking Helmet", "price": 1520, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_viking", "tags": ["EGGORG", "Yellow", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1297, "name": "Egg Cape", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggcape", "tags": ["EGGORG", "Yellow", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1298, "name": "Joker Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_joker", "tags": ["EGGORG", "Blue", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1299, "name": "Shield Hat", "price": 1520, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_shield", "tags": ["EGGORG", "Apr23", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1300, "name": "Valkyrie Helmet", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_valkyrie", "tags": ["Newsletter", "Blue", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 1301, "name": "Tattered Cape", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggcapeRust", "tags": ["Relic", "Drops2", "Brown", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1302, "name": "Gold Joker Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_jokerGold", "tags": ["Relic", "Drops2", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 1303, "name": "Rusty Viking Helmet", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_vikingRust", "tags": ["Relic", "Drops2", "Brown", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1304, "name": "Rusty Knight Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_knightRust", "tags": ["Relic", "Drops2", "Brown", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1305, "name": "JWBerry3D Glasses", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gamerglasses", "tags": ["Relic", "Red", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 1306, "name": "Ocean Glasses", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_oceanglasses", "tags": ["Relic", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1307, "name": "Tooth Survivor Bandana", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toothbandana", "tags": ["Dino", "May23", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 1308, "name": "Steggasauras Scales", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_stego", "tags": ["Dino", "May23", "Orange", "Green", "Dec23"] }, "is_available": false, "unlock": "purchase" }, { "id": 1309, "name": "Red Dino Tail", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dinotailred", "tags": ["Dino", "May23", "Yellow", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1310, "name": "Green Dino Tail", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dinotailgreen", "tags": ["Dino", "May23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1311, "name": "Dino Mouth Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dinomouth", "tags": ["Dino", "May23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1312, "name": "Dino Pterodactyl Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_DinoWings", "tags": ["Dino", "May23", "Green"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_dinowings"] }, { "id": 1313, "name": "Dino Triceratops Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dino", "tags": ["Dino", "Newsletter", "Orange"] }, "is_available": false, "unlock": "manual" }, { "id": 1314, "name": "Tablet Backpack", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_tabletpack", "tags": ["Mobile", "SepM23", "Red", "Egg"] }, "is_available": false, "unlock": "purchase" }, { "id": 1315, "name": "Telephone Hat ", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_telephone", "tags": ["Mobile", "AugM23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1316, "name": "Airplane Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Airplane", "tags": ["Sep23", "Premium", "White", "Blue"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_airplane"] }, { "id": 1317, "name": "Head Tail", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_headtails", "tags": ["Eggwalker2", "White", "Green", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1318, "name": "Eggpire Cap", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_imperial", "tags": ["Eggwalker2", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1319, "name": "Sci-fi Visor", "price": 6500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_obiwan", "tags": ["Eggwalker2", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1320, "name": "Cross Fighter Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_CrossWing", "tags": ["Eggwalker2", "Premium", "White", "Grey", "Gray", "Red", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_crosswing"] }, { "id": 1321, "name": "Pineapple Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pineapple", "tags": ["Summer", "JunM23", "Green", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1322, "name": "Kite Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kite", "tags": ["Summer", "JunM23", "Rainbow", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1323, "name": "UK Bucket Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_buckethat", "tags": ["Summer", "Newsletter", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 1324, "name": "Baseball Helmet", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_baseball", "tags": ["Sports", "JulyM23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1325, "name": "Football Helmet", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_football", "tags": ["Sports", "JulyM23", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1326, "name": "Swim Cap", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_swimcap", "tags": ["Sports", "JulyM23", "Oct23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1327, "name": "Frisbee Damage Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_frisbee", "tags": ["Sports", "JulyM23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1328, "name": "SPORTS headband", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_headband", "tags": ["Sports", "JulyM23", "Green", "Egg"] }, "is_available": false, "unlock": "purchase" }, { "id": 1329, "name": "Cone Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cone", "tags": ["Newsletter", "Sports", "JulyM23", "Orange"] }, "is_available": false, "unlock": "manual" }, { "id": 1330, "name": "Egg Yolk Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggyolk", "tags": ["Breakfast", "Egg", "White", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1331, "name": "Waffles Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_waffles", "tags": ["Breakfast", "Brown", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1332, "name": "Pancakes Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pancakes", "tags": ["Breakfast", "Brown", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1333, "name": "Teacup Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_teacup", "tags": ["Breakfast", "White", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1334, "name": "Captain Breakfast Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_captaincrunch", "tags": ["Breakfast", "Newsletter", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1335, "name": "Keyhole Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_keyhole", "tags": ["Scavenger", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1336, "name": "Distinguished Gentlemen Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pipe", "tags": ["Dec23", "Scavenger", "Brown", "Hair"] }, "is_available": false, "unlock": "purchase" }, { "id": 1337, "name": "Wizskull Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_wizskull", "tags": ["Scavenger", "Blue", "White", "Bone", "BWD"] }, "is_available": false, "unlock": "purchase" }, { "id": 1338, "name": "Tucked Pencil Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_pencilhair", "tags": ["Pencil2", "Sep23", "Yellow", "Hair"] }, "is_available": false, "unlock": "purchase" }, { "id": 1339, "name": "Slide Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_slide", "tags": ["Pencil2", "Sep23", "Blue", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1340, "name": "Scavenger Hunt Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scavenger", "tags": ["Pencil2", "Sep23", "Red", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1341, "name": "Rainbow Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_RainbowWings", "tags": ["Pencil2", "Feb24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_rainbow"] }, { "id": 1342, "name": "Paper Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_paper", "tags": ["Newsletter", "Pencil2", "Blue", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1343, "name": "Albino Book Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_snake", "tags": ["Sep22", "Drops3", "ABHS"] }, "is_available": false, "unlock": "manual" }, { "id": 1344, "name": "Heart Backpack", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_heartpack", "tags": ["Sep22", "Drops3", "Red", "Pink"] }, "is_available": false, "unlock": "manual" }, { "id": 1345, "name": "Deal with it Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_deal", "tags": ["Sep22", "Drops3", "Black", "Meme"] }, "is_available": false, "unlock": "manual" }, { "id": 1346, "name": "Kilzomatic Hat", "price": 6e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kilzomatic", "tags": ["Sep22", "Yellow", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1347, "name": "Sharkbucks Hat", "price": 6900, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sharkbucks", "tags": ["Sep22", "Pink", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 1348, "name": "The cap cap", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cap", "tags": ["Newsletter", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1349, "name": "Teggtris wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Tetris", "tags": ["Sep22", "Premium", "Rainbow"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_teggtris"] }, { "id": 1350, "name": "Scary Balloon Hat", "price": 1990, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_balloon", "tags": ["Halloween3", "OctM23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1351, "name": "Witch Cobwebs Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cobweb", "tags": ["Halloween3", "Newsletter", "OctM23", "Purple", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1352, "name": "Cauldron Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cauldron", "tags": ["Halloween3", "OctM23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1353, "name": "Mummy Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mummy", "tags": ["Halloween3", "OctM23", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1354, "name": "Black Cat Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kitten", "tags": ["Halloween3", "OctM23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1355, "name": "Dracula Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dracula", "tags": ["Halloween3", "OctM23", "White", "Grey", "Gray", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1356, "name": "Blood Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_BloodWings", "tags": ["Halloween3", "Jun23", "Red"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_bloodwing"] }, { "id": 1357, "name": "It's Corn Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_corn", "tags": ["NovM23", "Thanksgiving2", "Meme", "Yellow", "Food", "Nov23"] }, "is_available": false, "unlock": "purchase" }, { "id": 1358, "name": "NPS Clan Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_NPS", "tags": ["League"] }, "is_available": false, "unlock": "manual" }, { "id": 1359, "name": "Drone Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_drone", "tags": ["Badegg", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1360, "name": "Tactical Vest", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_tacticalvest", "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1361, "name": "Medbox Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_medbox", "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1362, "name": "Crash Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_crash", "tags": ["Badegg", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1363, "name": "Fall Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Fall", "tags": ["Badegg", "SepM23", "Orange", "Brown"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_hat_fall"] }, { "id": 1364, "name": "Ribbon Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_ribbon", "tags": ["Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1365, "name": "Santa hat & Beard", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_santabeard", "tags": ["Christmas2", "Newsletter", "Red", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1366, "name": "Sailor Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sailor", "tags": ["Mar24", "Newsletter", "White", "Seaman"] }, "is_available": false, "unlock": "manual" }, { "id": 1367, "name": "Party Hat 2023", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_party2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1368, "name": "2023 Headband", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1369, "name": "Holly Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Holly", "tags": ["Dec23", "Red", "Green"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_holy_wings"] }, { "id": 1370, "name": "Piano Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_piano", "tags": ["Rockstar", "JanM23", "Black", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 1371, "name": "Gramophone Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gramaphone", "tags": ["Rockstar", "JanM23", "Gold", "Yellow", "Brown", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 1372, "name": "Sound Wave Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Music", "tags": ["Rockstar", "Premium", "JanM23", "Blue", "Purple", "Blurple", "Music"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_soundwave"] }, { "id": 1373, "name": "Fancy Band Hat", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fancyband", "tags": ["Rockstar", "JanM23", "Blue", "Green", "Gold", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 1374, "name": "Winter Scarf", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scarf", "tags": ["Groundhog", "Feb23", "Red", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 1375, "name": "Bull hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bull", "tags": ["farm", "FebM23", "Bone", "Brown", "Gray", "Grey"] }, "is_available": false, "unlock": "purchase" }, { "id": 1376, "name": "Farmer Shirt", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_farmer", "tags": ["farm", "FebM23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1377, "name": "Cowbell Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cowbell", "tags": ["farm", "FebM23", "Silver"] }, "is_available": false, "unlock": "purchase" }, { "id": 1378, "name": "Barrel Eye", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_barrel", "tags": ["Drops4", "Mar23", "AugM23", "Brown", "Silver", "Gray", "Grey"] }, "is_available": false, "unlock": "purchase" }, { "id": 1379, "name": "Kiwi Hat", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kiwi", "tags": ["Drops4", "Mar23", "AugM23", "Yellow", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1380, "name": "Eggscellent Hat", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggscellent", "tags": ["Drops4", "Mar23", "AugM23", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1381, "name": "KJs Dad", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_oldman", "tags": ["Drops4", "Mar23", "Old", "Grey", "Gray", "Meme", "Hair"] }, "is_available": false, "unlock": "purchase" }, { "id": 1382, "name": "Novosuper Helmet", "price": 1e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_novo", "tags": ["Drops4", "Mar23", "Black", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1383, "name": "Bracket Shell Sombrero", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_banana", "tags": ["Drops4", "Mar23", "Yellow", "Blue", "Bananas"] }, "is_available": false, "unlock": "manual" }, { "id": 1384, "name": "The Mask of Paradise", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_paradise", "tags": ["Drops4", "Mar23", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1385, "name": "xQc Hair", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_xhair", "tags": ["Drops4", "Mar23", "White", "Black", "Red", "Meme"] }, "is_available": false, "unlock": "manual" }, { "id": 1386, "name": "Marshmallow Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_marshmallow", "tags": ["Drops4", "Mar23", "White", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1387, "name": "Big Brain Hat", "price": 100, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_brain", "tags": ["Drops4", "Mar23", "AugM23", "OctM23", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 1388, "name": "Fusion Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fusion", "tags": ["Newsletter", "Mar23", "White", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1389, "name": "Harp Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Harp", "tags": ["Premium", "Mar23", "Gold"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_harp"] }, { "id": 1390, "name": "Longhorn Bros", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_longhorns", "tags": ["Bros", "MarM23", "Bone", "Yellow", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1391, "name": "Purdue Bros", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_purdue", "tags": ["Bros", "MarM23", "Yellow", "White", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1392, "name": "Scoreboard Bros", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scoreboard", "tags": ["Bros", "MarM23", "Blue", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1393, "name": "Drenched Bros", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gamerjuice", "tags": ["Bros", "MarM23", "Blue", "Grey", "Gray", "Orange", "Electrolytes"] }, "is_available": false, "unlock": "purchase" }, { "id": 1394, "name": "Hooped Hat", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Hoop", "tags": ["Bros", "MarM23", "White", "Red"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_hooped"] }, { "id": 1395, "name": "Brown Wizard Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_brownwizard", "tags": ["Heroes", "Apr23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1396, "name": "Elf Ears Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_elfear", "tags": ["Heroes", "Apr23", "Grey", "Gray", "Hair"] }, "is_available": false, "unlock": "purchase" }, { "id": 1397, "name": "Dwarf Beard", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dwarf", "tags": ["Heroes", "Apr23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 1398, "name": "Gelatinous Cube Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cube", "tags": ["Monsters", "Apr23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1399, "name": "Purple Worm Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_wurm", "tags": ["Monsters", "Apr23", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 1400, "name": "Question Block Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_MysteryWings", "tags": ["AprM23", "Aug23", "JanM24", "White", "Yellow", "?"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_qwings"] }, { "id": 1401, "name": "Green Dino Head", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_greendino", "tags": ["Dino2", "May23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1402, "name": "Blue Dino Tail", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dinotailblue", "tags": ["Dino2", "May23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1403, "name": "Caveman Hair", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_caveman", "tags": ["Dino2", "May23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1404, "name": "Leopard Sash", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_skinsash", "tags": ["Dino2", "May23", "Orange", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1405, "name": "Tiger Sash", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_tigersash", "tags": ["Dino2", "May23", "Newsletter", "Orange", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 1406, "name": "Egg Chest Hat", "price": 3e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_goldchest", "tags": ["Eggflation", "MayM23", "Gold", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 1407, "name": "Golden Nugget Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_goldnugget", "tags": ["Eggflation", "MayM23", "Gold"] }, "is_available": true, "unlock": "purchase" }, { "id": 1408, "name": "Photobooth Top Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_boothtophat", "tags": ["Photo", "Jun23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1409, "name": "Photobooth Bow", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_boothbow", "tags": ["Photo", "Jun23", "Black", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1410, "name": "Photobooth Crown", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_boothcrown", "tags": ["Photo", "Jun23", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 1411, "name": "Photobooth Cake", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_boothcake", "tags": ["Newsletter", "Photo", "Jun23", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 1412, "name": "Red Snorkel", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_snorkelred", "tags": ["Summer2", "JunM23", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1413, "name": "Blue Snorkel", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_snorkelblue", "tags": ["Summer2", "JunM23", "Red", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1414, "name": "Beach Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_beach", "tags": ["Summer2", "JunM23", "Yellow", "Green", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1415, "name": "Sandcastle Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sandcastle", "tags": ["Summer2", "JunM23", "Gold", "Yellow", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1416, "name": "Crab Hat", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_crab", "tags": ["Summer2", "JunM23", "Red", "Meme"] }, "is_available": false, "unlock": "purchase" }, { "id": 1417, "name": "Octopus Surfboard", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Octopus", "tags": ["Summer2", "JunM23", "Brown"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_surf"] }, { "id": 1418, "name": "Equinox Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_equinox", "tags": ["Equinox", "July23", "Gold", "Yellow", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1419, "name": "Equinox Sun Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_equinoxSun", "tags": ["Equinox", "July23", "Gold", "Yellow", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1420, "name": "Equinox Moon Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_equinoxMoon", "tags": ["Equinox", "July23", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1421, "name": "Bonsai Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bonsai", "tags": ["Equinox", "July23", "Blue", "Yellow", "Green", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1422, "name": "Skull Trio Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_skulls", "tags": ["Newsletter", "July23", "Bone", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1423, "name": "Scales of Justice Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Scales", "tags": ["July23", "Gold"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_scales"] }, { "id": 1424, "name": "Biker Helmet", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_extremehelm", "tags": ["Sports2", "JulyM23", "Black", "Red", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1425, "name": "Climbing Gear Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_extremeclimb", "tags": ["Sports2", "JulyM23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1426, "name": "Ski Bum Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_extremeskis", "tags": ["Sports2", "JulyM23", "Rainbow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1427, "name": "Stickers Helmet", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_stickers", "tags": ["Sports2", "JulyM23", "Black", "Egg"] }, "is_available": false, "unlock": "purchase" }, { "id": 1428, "name": "Hang Glider Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Glider", "tags": ["Sports2", "JulyM23", "Rainbow"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_glider"] }, { "id": 1429, "name": "Red Kart", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kartRed", "tags": ["Kart", "Aug23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1430, "name": "Green Kart", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kartGreen", "tags": ["Kart", "Aug23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1431, "name": "Pink Kart", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kartPink", "tags": ["Kart", "Aug23", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 1432, "name": "Yellow Kart", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_kartYellow", "tags": ["Kart", "Aug23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1433, "name": "Piranha Hat", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_piranha", "tags": ["Kart", "Aug23", "Red", "White", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1434, "name": "Big Biter Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_chomp", "tags": ["Kart", "Aug23", "Blue", "Chomp"] }, "is_available": false, "unlock": "purchase" }, { "id": 1435, "name": "Gang Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_gang", "tags": ["SL", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1436, "name": "Fluffly Meteor Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fluffy", "tags": ["Drops5", "AugM23", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 1437, "name": "King Hayden Crown", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_hayden", "tags": ["Drops5", "AugM23", "Gold"] }, "is_available": false, "unlock": "manual" }, { "id": 1438, "name": "Anarchy Arden", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_academymale", "tags": ["Sep23", "Pencil3", "Egg", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1439, "name": "Anarchy Ashley", "price": 2500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_academyfemale", "tags": ["Sep23", "Pencil3", "Egg", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1440, "name": "Dunce Cap", "price": 4e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dunce", "tags": ["Sep23", "Pencil3", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1441, "name": "The Toolbelt", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toolbelt", "tags": ["Sep23", "Pencil3", "Newsletter", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 1442, "name": "Wrestle Shoes Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_shoetie", "tags": ["SepM23", "WBs", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1443, "name": "Wrestling Belt", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_wrestlebelt", "tags": ["SepM23", "WBs", "Gold", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1444, "name": "Wrestling Ring Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_wrestlering", "tags": ["SepM23", "WBs", "White", "Black", "Red", "White", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 1445, "name": "The Grand Entrance Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Firework", "tags": ["SepM23", "WBs", "Red", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_wbs"] }, { "id": 1446, "name": "Angler Fish Hat", "price": 3500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_angler", "tags": ["Oct23", "Halloween4", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1447, "name": "Hungry Shark Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_shark", "tags": ["Oct23", "Halloween4", "Grey", "Gray", "Silver"] }, "is_available": false, "unlock": "purchase" }, { "id": 1448, "name": "Baby Ghost Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_babyghost", "tags": ["Oct23", "Halloween4", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1449, "name": "Captain Inksalot Hat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_squidpatch", "tags": ["Oct23", "Halloween4", "Newsletter", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 1450, "name": "Demon Pixel Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_PixelDemon", "tags": ["Oct23", "Halloween4", "Black"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_demonpixel"] }, { "id": 1451, "name": "Purple Witch's Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_purplewitch", "tags": ["OctM23", "Halloween4", "Purple"] }, "is_available": false, "unlock": "purchase" }, { "id": 1452, "name": "Wednesday Morning Hair", "price": 2020, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_addams", "tags": ["OctM23", "Halloween4", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 1453, "name": "Ectoplasmic Goo", "price": 1980, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_slime", "tags": ["OctM23", "Halloween4", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 1454, "name": "Stapled Bear Friend", "price": 2010, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_bear", "tags": ["OctM23", "Halloween4", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1455, "name": "Ancient Egg Hat", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_ruins", "tags": ["Nov23", "Mayan", "Green", "Gray", "Grey", "Stone", "Plant"] }, "is_available": false, "unlock": "purchase" }, { "id": 1456, "name": "The Ruins Explorer", "price": 250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_ruinsexplorer", "tags": ["Nov23", "Mayan", "Brown", "Stone", "Plant", "Gray", "Grey"] }, "is_available": false, "unlock": "purchase" }, { "id": 1457, "name": "Indianapolis Jones", "price": 1750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_explorer", "tags": ["Nov23", "Mayan", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 1458, "name": "Mayan Warrior Mask", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mayan", "tags": ["Nov23", "Mayan", "Brown", "Green", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1459, "name": "Meso-Mage Mask", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mayan2", "tags": ["Nov23", "Mayan", "Brown", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 1460, "name": "The Fallen Explorer", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_overgrown", "tags": ["Nov23", "Newsletter", "Mayan", "Red", "Green", "Mushroom"] }, "is_available": false, "unlock": "manual" }, { "id": 1461, "name": "Ruins Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_Ruins", "tags": ["Nov23", "Mayan", "Green", "Gray", "Grey"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_mayan"] }, { "id": 1462, "name": "Fall Pilgrim Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fallhat", "tags": ["NovM23", "Thanksgiving3", "Green", "Gray", "Grey"] }, "is_available": false, "unlock": "purchase" }, { "id": 1463, "name": "Kindergarden Turkey", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_sillyturkey", "tags": ["NovM23", "Thanksgiving3", "Green", "Gray", "Grey"] }, "is_available": false, "unlock": "purchase" }, { "id": 1464, "name": "All the Fixin's Hat", "price": 1250, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_dinner", "tags": ["NovM23", "Thanksgiving3", "Green", "Gray", "Grey"] }, "is_available": false, "unlock": "purchase" }, { "id": 1465, "name": "Bread Cat", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_toastcat", "tags": ["Xsolla", "Brown", "Meow", "Kitty", "Kitten"] }, "is_available": false, "unlock": "manual", "activeProduct": false, "sku": ["item_hat_breadcat"] }, { "id": 1466, "name": "Wreathed Egg", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_wreath", "tags": ["Christmas3", "Dec23", "Green", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1467, "name": "Frosty", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_snowman", "tags": ["Christmas3", "Dec23", "White", "Yellow", "Carrot"] }, "is_available": false, "unlock": "purchase" }, { "id": 1468, "name": "Mistletoe Hat", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mistletoe", "tags": ["Christmas3", "Dec23", "Green", "Red", "Kiss"] }, "is_available": false, "unlock": "purchase" }, { "id": 1469, "name": "Eggsmas Tree", "price": 500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_christmastree", "tags": ["Christmas3", "Dec23", "Green", "Red", "Star"] }, "is_available": false, "unlock": "purchase" }, { "id": 1470, "name": "Snow Owl Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_SnowOwl", "tags": ["Christmas3", "Dec23", "Green", "Red"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_owl"] }, { "id": 1471, "name": "Egg'Noggin", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_eggnog", "tags": ["Christmas3", "Dec23", "Yellow", "Red", "Newsletter"] }, "is_available": false, "unlock": "manual" }, { "id": 1472, "name": "Party Hat 2024", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_party2024", "tags": ["NewYears", "2024", "DecM23", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1473, "name": "2024 Headband", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_2024", "tags": ["NewYears", "2024", "DecM23", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1474, "name": "Discord Dev Day Crown", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_discorders", "tags": ["promo", "Blurple"] }, "is_available": false, "unlock": "manual" }, { "id": 1475, "name": "Disco Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_NewYearsDisco", "tags": ["NewYears", "2024", "DecM23", "Blurple"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_disco"] }, { "id": 1476, "name": "The CyberCluck", "price": 125e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_cybercar", "tags": ["Cybertruck", "Truck", "Musk", "Silver", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 1477, "name": "Lightning Helmet", "price": 5e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_lightninghelm", "tags": ["JanM24", "Racer", "Orange"] }, "is_available": true, "unlock": "purchase" }, { "id": 1478, "name": "Skull Helmet", "price": 1e4, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_skullhelm", "tags": ["JanM24", "Racer", "Gray", "Grey", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 1479, "name": "Targeted Bandana", "price": 7500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_targetbandana", "tags": ["JanM24", "Black", "Racer"] }, "is_available": true, "unlock": "purchase" }, { "id": 1480, "name": "The Racing Spoiler Wings", "price": 5, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_SpoilerWings", "tags": ["JanM24", "Egg", "Racer", "Orange"] }, "is_available": true, "unlock": "premium", "activeProduct": false, "sku": ["item_hat_racecar"] }, { "id": 1481, "name": "Cute Fox Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fox", "tags": ["Feb24", "Critters", "Brown", "Orange", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1482, "name": "Cute Mouse Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_mouse", "tags": ["Feb24", "Critters", "Brown", "Orange", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1483, "name": "Cute Deer Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_fawn", "tags": ["Feb24", "Critters", "Brown", "Orange", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1484, "name": "Cute Squirrel Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_squirrel", "tags": ["Feb24", "Critters", "Brown", "Orange", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1485, "name": "Cute Owl Hat", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_owl", "tags": ["Feb24", "Critters", "Brown", "Orange", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 1486, "name": "Shell Wiki Staff Headphones", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_wikiStaff", "tags": ["Feb24", "Critters", "Brown", "Orange", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 1487, "name": "Argentina Scarf", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scarfArgentina", "tags": ["FebM24", "SBros", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1488, "name": "England Scarf", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scarfEngland", "tags": ["FebM24", "SBros", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1489, "name": "America Scarf", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scarfAmerica", "tags": ["FebM24", "SBros", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1490, "name": "Brazil Scarf", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scarfBrazil", "tags": ["FebM24", "SBros", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1491, "name": "Portugal Scarf", "price": 750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_scarfPortugal", "tags": ["FebM24", "SBros", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 1492, "name": "Patchwork Cap", "price": 1500, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_patchwork", "tags": ["Mar24", "StPatricksDay", "Brown", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1493, "name": "Leprechaun Mini Hat", "price": 2e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_leprechaunsmall", "tags": ["Mar24", "StPatricksDays", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 1494, "name": "Bad Bunny Mask", "price": 2147483647, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_premium_ScaryBunny", "tags": ["Mar24", "Darko", "Grey", "Gray", "Teeth"] }, "is_available": true, "unlock": "premium" }, { "id": 1495, "name": "Slayaway Bunnyface", "price": 1750, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_slashbunny", "tags": ["MarM24", "Skullface", "Camp", "White", "Red", "Teeth", "Easter", "Bunny", "Carrot"] }, "is_available": true, "unlock": "purchase" }, { "id": 1496, "name": "Chocolate Drip", "price": 1e3, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_chocolate", "tags": ["MarM24", "Egg", "Brown", "Easter"] }, "is_available": true, "unlock": "purchase" }, { "id": 1497, "name": "Trucker Hat", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_trucker", "tags": ["MarM24", "Default", "Brown"] }, "is_available": true, "unlock": "default" }, { "id": 1498, "name": "Winner Winner Chicken Dinner", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_chicknwinner", "tags": ["MarM24", "Default", "Brown"] }, "is_available": true, "unlock": "default" }, { "id": 1499, "name": "Newsboi Hat", "price": 0, "item_type_id": 1, "item_type_name": "Hat", "category_name": "Hats", "exclusive_for_class": null, "item_data": { "meshName": "hat_newsboy", "tags": ["MarM24", "Default", "Brown"] }, "is_available": true, "unlock": "default" }, { "id": 2001, "name": "Target Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 0, "tags": ["Default", "Red", "Blue", "Yellow"] }, "is_available": true, "unlock": "default" }, { "id": 2002, "name": "No Sign Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 0, "tags": ["Default", "Red"] }, "is_available": true, "unlock": "default" }, { "id": 2003, "name": "Question Mark Stamp?", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 0, "tags": ["Default", "Black", "?"] }, "is_available": true, "unlock": "default" }, { "id": 2004, "name": "Peace Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 0, "tags": ["Default", "Black"] }, "is_available": true, "unlock": "default" }, { "id": 2005, "name": "Thumbs Up Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 0, "tags": ["Default", "White"] }, "is_available": true, "unlock": "default" }, { "id": 2006, "name": "Pablo Smile Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 0, "tags": ["Default", "Happy", "Face", "Yellow"] }, "is_available": true, "unlock": "default" }, { "id": 2007, "name": "Skull & Crossbones Stamp", "price": 200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 2, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2008, "name": "Tyrant Stamp", "price": 200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 3, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2009, "name": "Shifty Eye Stamp", "price": 200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 5, "tags": ["Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 2010, "name": "Arrow & Heart Stamp", "price": 200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 6, "tags": ["Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2011, "name": "Grade A Stamp", "price": 300, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 1, "tags": ["Red", "USDA"] }, "is_available": true, "unlock": "purchase" }, { "id": 2012, "name": "Anarchy Sign Stamp", "price": 300, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 1, "tags": ["Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2013, "name": "Derp Face Stamp", "price": 300, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 2, "tags": ["Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 2014, "name": "Wolf Stamp", "price": 300, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 5, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2015, "name": "Chicken Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 6, "tags": ["Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 2016, "name": "Phoenix Stamp", "price": 600, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 7, "tags": ["Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2017, "name": "Alien Stamp", "price": 600, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 7, "tags": ["Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 2018, "name": "Dapper Mustache Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 5, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2019, "name": "Happy Bear Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 8, "tags": ["Pink", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2020, "name": "Ghost Face Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 8, "tags": ["Halloween", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2021, "name": "Jack Face Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 8, "tags": ["Halloween", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2022, "name": "Cracks Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 9, "tags": ["Halloween", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2023, "name": "Bat Face Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 9, "tags": ["Halloween", "Oct23", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 2024, "name": "Cthulhu Fhtagn Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 9, "tags": ["Halloween", "Oct23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2025, "name": "Elder Sign Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 9, "tags": ["Halloween", "Oct23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2026, "name": "Scary Teeth Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 9, "tags": ["Halloween", "Oct23", "Smile", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2027, "name": "Monster Tongue Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 9, "tags": ["Halloween", "Oct23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2028, "name": "Spooky Lady Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 9, "tags": ["Halloween", "Oct23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2029, "name": "Clown Face Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 10, "tags": ["Halloween", "Oct23", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2030, "name": "Stitch Face Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 10, "tags": ["Halloween", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2031, "name": "Devil Face Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 10, "tags": ["Halloween", "Oct23", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2032, "name": "Face Mask Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 10, "tags": ["Halloween", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2033, "name": "Hand Turkey Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 10, "tags": ["NovM23", "Thanksgiving"] }, "is_available": false, "unlock": "purchase" }, { "id": 2034, "name": "Turkey Face Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 10, "tags": ["NovM23", "Thanksgiving"] }, "is_available": false, "unlock": "purchase" }, { "id": 2035, "name": "Turkey Crossbones Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 10, "tags": ["NovM23", "Thanksgiving", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2036, "name": "Reindeer Face Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 11, "tags": ["Dec23", "Christmas", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2037, "name": "Gingerbread Cookie Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 11, "tags": ["Dec23", "Christmas", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2038, "name": "Santa Skull Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 11, "tags": ["Christmas2", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2039, "name": "2019 Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 11, "tags": ["NewYears", "2019", "Yellow", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 2040, "name": "Fireworks Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 11, "tags": ["NewYears", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2041, "name": "Midnight Clock Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 11, "tags": ["NewYears"] }, "is_available": false, "unlock": "purchase" }, { "id": 2042, "name": "Stressed Out Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 7, "tags": ["Newsletter", "Face"] }, "is_available": false, "unlock": "manual" }, { "id": 2043, "name": "Chicken Finger Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 8, "tags": ["Newsletter"] }, "is_available": false, "unlock": "manual" }, { "id": 2044, "name": "Lyerpald Stamp ", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 8, "tags": ["Contentcreator"] }, "is_available": false, "unlock": "manual" }, { "id": 2045, "name": "Groundhog Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 11, "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 2046, "name": "Winter Snowflake Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 12, "tags": ["Groundhog", "Feb23", "Blue", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 2047, "name": "Spring Flower Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 12, "tags": ["Groundhog", "Feb23", "Pink", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 2048, "name": "Broken Heart Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 12, "tags": ["ValentinesDay", "Red", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 2049, "name": "Rose Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 12, "tags": ["ValentinesDay", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2050, "name": "Anatomical Heart Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 12, "tags": ["ValentinesDay", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 2051, "name": "Shamrock Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 12, "tags": ["StPatricksDay", "MarM23", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2052, "name": "Ginger Beard Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 12, "tags": ["StPatricksDay", "MarM23", "Brown", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2053, "name": "Pot of Gold Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 13, "tags": ["StPatricksDay", "MarM23", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2054, "name": "Bunny Face Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 13, "tags": ["Easter", "AprM23", "Heart", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2055, "name": "Easter Egg Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 13, "tags": ["Easter", "AprM23", "Blue", "White", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2056, "name": "Golden Easter Egg Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 13, "tags": ["Easter", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2057, "name": "Shell League Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 13, "tags": ["League"] }, "is_available": true, "unlock": "purchase" }, { "id": 2058, "name": "TXC Clan Logo Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 13, "tags": ["Green", "Blue", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2071, "name": "GOD Clan Logo", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 15, "tags": ["Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 2059, "name": "Sherrif Star Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 6, "tags": ["Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2060, "name": "Rainbow Cloud Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 5, "tags": ["Cute"] }, "is_available": true, "unlock": "purchase" }, { "id": 2061, "name": "Angel Wings Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 6, "tags": ["Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2062, "name": "GoE Sigil - Wolf Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 13, "tags": ["GameOfEggs", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 2063, "name": "GoE Sigil - Lion Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 14, "tags": ["GameOfEggs", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2064, "name": "GoE Sigil - Bird Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 14, "tags": ["GameOfEggs", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 2065, "name": "GoE Sigil - Stag Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 14, "tags": ["GameOfEggs", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2066, "name": "GoE Sigil - Fish Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 14, "tags": ["GameOfEggs", "Orange"] }, "is_available": true, "unlock": "purchase" }, { "id": 2067, "name": "GoE Sigil - Squid Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 14, "tags": ["GameOfEggs", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2068, "name": "GoE Sigil - Sun Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 14, "tags": ["GameOfEggs", "Orange", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2069, "name": "GoE Sigil - Flower Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 14, "tags": ["GameOfEggs", "Green", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2070, "name": "GoE Sigil - Dragon Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 15, "tags": ["GameOfEggs", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2072, "name": "4th of July Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 15, "tags": ["July4", "Red", "Blue", "Fireworks"] }, "is_available": false, "unlock": "purchase" }, { "id": 2073, "name": "SL MVP Division A Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 15, "tags": ["League"] }, "is_available": false, "unlock": "manual" }, { "id": 2074, "name": "SL MVP Division B Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 15, "tags": ["League"] }, "is_available": false, "unlock": "manual" }, { "id": 2075, "name": "CRGI Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 15, "tags": ["League", "Dog"] }, "is_available": false, "unlock": "manual" }, { "id": 2076, "name": "Robot Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 6, "tags": ["Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 2077, "name": "Poop Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 7, "tags": ["Brown", "Poop"] }, "is_available": true, "unlock": "purchase" }, { "id": 2078, "name": "Heart Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 1, "tags": ["Cards", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2079, "name": "Spade Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 1, "tags": ["Cards", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2080, "name": "Club Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 1, "tags": ["Cards", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2081, "name": "Diamond Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 1, "tags": ["Cards", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2082, "name": "What Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 2, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2083, "name": "Yes Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 2, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2084, "name": "No Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 2, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2085, "name": "Ribcage Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 5, "tags": ["Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2086, "name": "Angry Cartridge Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 8, "tags": ["Grey", "Gray", "Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2087, "name": "DXG Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 0, "tags": ["League"] }, "is_available": false, "unlock": "manual" }, { "id": 2088, "name": "Tired Space Goblin Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 2, "tags": ["Eggwalker", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2089, "name": "Angry Space Dog Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 3, "tags": ["Eggwalker", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2090, "name": "No Trying Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 4, "tags": ["Eggwalker", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2091, "name": "Disgruntled Space Weasel Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 5, "tags": ["Eggwalker", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2092, "name": "White Beard Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 1, "tags": ["Newsletter", "Christmas", "Santa"] }, "is_available": false, "unlock": "manual" }, { "id": 2093, "name": "Strong Egg Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 5, "tags": ["Newsletter", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 2094, "name": "New Years 2020 Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 6, "tags": ["NewYears", "2020", "Yellow", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2095, "name": "Bad Eggs For Life Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 8, "tags": ["BadEggsForLife", "Jun23", "MarM24", "premFeatTwo"] }, "is_available": true, "unlock": "purchase" }, { "id": 2096, "name": "Pixel Heart Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 9, "tags": ["Newsletter", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 2097, "name": "Eggy Cash Face Stamp", "price": 5e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 15, "tags": ["EggyCash", "Face", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2098, "name": "DXG Clan Logo 2 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 10, "tags": ["League"] }, "is_available": false, "unlock": "manual" }, { "id": 2099, "name": "Raid Land Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 11, "tags": ["RaidLand"] }, "is_available": false, "unlock": "purchase" }, { "id": 2100, "name": "Egg Org Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 12, "tags": ["AprilFools", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2101, "name": "MVP 2020 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 13, "tags": ["League"] }, "is_available": false, "unlock": "manual" }, { "id": 2102, "name": "TXC Clan Skull Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 14, "tags": ["League", "Purple"] }, "is_available": false, "unlock": "manual" }, { "id": 2103, "name": "Toxic Skull Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 15, "tags": ["Rotten", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 2104, "name": "Toxic Nuke Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 0, "tags": ["Rotten", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 2105, "name": "Toxic Derp Face Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 1, "tags": ["Rotten", "Green", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2106, "name": "Facepaint Heart Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 5, "tags": ["Rockstar", "JanM23", "Pink", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 2107, "name": "Facepaint Star Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 6, "tags": ["Rockstar", "JanM23", "Black", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 2108, "name": "Facepaint Lightning Bolt Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 4, "tags": ["Rockstar", "JanM23", "Yellow", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 2109, "name": "Pink Starburst Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 7, "tags": ["Galeggsy", "AprM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2110, "name": "Alien Eyes 1 Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 8, "tags": ["Galeggsy", "AprM23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2111, "name": "Alien Eyes 2 Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 9, "tags": ["Galeggsy", "AprM23", "Face", "Cute"] }, "is_available": false, "unlock": "purchase" }, { "id": 2112, "name": "Flame Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 7, "tags": ["Newsletter", "Fire", "Red", "Orange", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 2113, "name": "Discord Mod Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 13, "tags": ["mod"] }, "is_available": false, "unlock": "manual" }, { "id": 2114, "name": "Black Tie Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 14, "tags": ["MercZone", "Suit", "Tie"] }, "is_available": false, "unlock": "manual" }, { "id": 2115, "name": "Red Tie Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 15, "tags": ["MercZone", "Suit", "Tie"] }, "is_available": false, "unlock": "manual" }, { "id": 2116, "name": "Pink Tie Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 0, "tags": ["MercZone", "Suit", "Tie"] }, "is_available": false, "unlock": "manual" }, { "id": 2117, "name": "Killstreak Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 1, "tags": ["Killstreak", "Smile", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 2118, "name": "Red Rooster Wings Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 10, "tags": ["Chicken"] }, "is_available": false, "unlock": "purchase" }, { "id": 2119, "name": "White Rooster Wings Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 11, "tags": ["Chicken"] }, "is_available": false, "unlock": "purchase" }, { "id": 2120, "name": "Gold Rooster Wings Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 12, "tags": ["Chicken", "July23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2121, "name": "Ugly Jason Face Stamp", "price": 1300, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 2, "tags": ["f13"] }, "is_available": true, "unlock": "purchase" }, { "id": 2122, "name": "Little Happy Stamp", "price": 1005, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 3, "tags": ["Stampede", "Face", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2123, "name": "Angry Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 4, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2124, "name": "Why Stamp", "price": 1005, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 5, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2125, "name": "Influenced Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 6, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2126, "name": "Nervous Crush Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 7, "tags": ["Stampede", "Face", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2127, "name": "Girly Eyes Stamp", "price": 1005, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 8, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2128, "name": "Big Smile Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 9, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2129, "name": "Cyclops Face Stamp", "price": 1005, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 10, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2130, "name": "Grumpy Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 11, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2131, "name": "Big Happy Stamp", "price": 1005, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 12, "tags": ["Stampede", "Smile", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2132, "name": "Scared Stamp", "price": 1005, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 13, "tags": ["Stampede", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2133, "name": "This Guy Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 14, "tags": ["Stampede", "Face", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2134, "name": "Tumble Dude Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 15, "tags": ["Stampede", "White", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2135, "name": "Thee_Owl Angry Face Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 0, "tags": ["Stampede"] }, "is_available": true, "unlock": "purchase" }, { "id": 2136, "name": "Blow Face Stamp", "price": 3e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 1, "tags": ["Stampede"] }, "is_available": true, "unlock": "purchase" }, { "id": 2137, "name": "Whip Em Stamp", "price": 3e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 2, "tags": ["Stampede", "Blue", "Whisk"] }, "is_available": true, "unlock": "purchase" }, { "id": 2138, "name": "Baby on Board Stamp", "price": 3e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 3, "tags": ["Stampede", "Chick", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2139, "name": "Thee_Owl Scared Face Stamp", "price": 3e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 4, "tags": ["Stampede"] }, "is_available": true, "unlock": "purchase" }, { "id": 2140, "name": "Yin Yang Chicken Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 5, "tags": ["Stampede", "Black", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 2141, "name": "Blue Wizard Guy Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 8, "tags": ["Newsletter", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 2142, "name": "God Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 6, "tags": ["League", "Red", "Orange"] }, "is_available": false, "unlock": "manual" }, { "id": 2143, "name": "Wero Face Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 7, "tags": ["Wero", "Beard"] }, "is_available": true, "unlock": "purchase" }, { "id": 2144, "name": "New Years 2021 Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 8, "tags": ["NewYears", "2021", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2145, "name": "Thee_Owl Logo Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 9, "tags": ["ThreeOwl", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 2146, "name": "Biggest Mouth Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 5, "tags": ["Newsletter", "Ahh"] }, "is_available": false, "unlock": "manual" }, { "id": 2147, "name": "C4bra Ram Outfit Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 7, "tags": ["C4bra"] }, "is_available": true, "unlock": "purchase" }, { "id": 2148, "name": "Hazmatt Thumbs Up Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 8, "tags": ["Hazmat", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2149, "name": "Hazmatt POG Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 9, "tags": ["Hazmat", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2150, "name": "Pixel Tech Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 10, "tags": ["Pixel", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 2151, "name": "Pixel Chicken Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 11, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2152, "name": "Pixel Gun Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 12, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2153, "name": "Pixel Robot Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 13, "tags": ["Pixel", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 2154, "name": "Pixel Shield Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 14, "tags": ["Pixel", "Eggs"] }, "is_available": true, "unlock": "purchase" }, { "id": 2155, "name": "Pixel Egg Splat Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 15, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2156, "name": "Pixel Swords Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 0, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2157, "name": "Pixel Happy Face Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 1, "tags": ["Pixel", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2158, "name": "Pixel Angry Face Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 2, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2159, "name": "Pixel Annoyed Face Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 3, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2160, "name": "Pixel Dead Face Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 4, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2161, "name": "Pixel Deal With It Sunglasses Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 5, "tags": ["Pixel"] }, "is_available": true, "unlock": "purchase" }, { "id": 2162, "name": "Angry Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 12, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2163, "name": "Cat Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 13, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2164, "name": "Crazy Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 14, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2165, "name": "Dog Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 15, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2166, "name": "Evil Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 0, "tags": ["Mouth", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2167, "name": "Grinning Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 1, "tags": ["Mouth", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2168, "name": "Happy Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 2, "tags": ["Mouth", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2169, "name": "Laughing Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 3, "tags": ["Mouth", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2170, "name": "Pirate Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 4, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2171, "name": "Sick Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 5, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2172, "name": "Smiling Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 6, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2173, "name": "Tongue-Out Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 7, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2174, "name": "Upset Mouth Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 8, "tags": ["Mouth"] }, "is_available": true, "unlock": "purchase" }, { "id": 2175, "name": "Dead BW Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 10, "tags": ["EGGORG", "Wizard", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2176, "name": "Egg Org Spokesperson Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 11, "tags": ["EGGORG"] }, "is_available": false, "unlock": "purchase" }, { "id": 2177, "name": "Aries Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 12, "tags": ["League", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 2178, "name": "Diablo Frown Stamp", "price": 100, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 9, "tags": ["EGGORG"] }, "is_available": false, "unlock": "purchase" }, { "id": 2179, "name": "Train Ticket Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 11, "tags": ["Trains", "Cars"] }, "is_available": true, "unlock": "purchase" }, { "id": 2180, "name": "Train Engine Stamp", "price": 3e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 13, "tags": ["Trains", "Cars", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2181, "name": "All Aboard Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 14, "tags": ["Trains", "Cars"] }, "is_available": true, "unlock": "purchase" }, { "id": 2182, "name": "Pain Train's Comin Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 15, "tags": ["Trains", "Cars"] }, "is_available": true, "unlock": "purchase" }, { "id": 2183, "name": "Random Life Logo Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 0, "tags": ["Random", "RL"] }, "is_available": true, "unlock": "purchase" }, { "id": 2184, "name": "Mystery QR Code", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 5 }, "is_available": true, "unlock": "purchase" }, { "id": 2185, "name": "Ethan Gamer Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 4, "tags": ["EthanGamer", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2186, "name": "Red Aries Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 10, "tags": ["League"] }, "is_available": false, "unlock": "manual" }, { "id": 2187, "name": "Toilet Paper Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 6, "tags": ["TP", "Poop"] }, "is_available": false, "unlock": "purchase" }, { "id": 2188, "name": "Water Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 8, "tags": ["Summer", "JunM23", "Blue", "Water"] }, "is_available": false, "unlock": "purchase" }, { "id": 2189, "name": "Popsicle Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 6, "tags": ["Summer", "JunM23", "Pink", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2190, "name": "Sun Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 7, "tags": ["Summer", "JunM23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2191, "name": "Postage Stamp", "price": 3e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 9, "tags": ["Summer", "JunM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2192, "name": "Blue Wizard Skull Stamp", "price": 1200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 6, "tags": ["BWD"] }, "is_available": true, "unlock": "purchase" }, { "id": 2193, "name": "Lyerpald Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 8, "tags": ["Dog", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 2194, "name": "SL NA#1 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 1, "tags": ["League", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 2195, "name": "SL EU#1 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 2, "tags": ["League", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 2196, "name": "SL OCE#1 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 3, "tags": ["League", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 2197, "name": "I <3 New Yolker Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 11, "tags": ["Newsletter", "Heart", "NY"] }, "is_available": false, "unlock": "manual" }, { "id": 2198, "name": "Egg Heart Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 12, "tags": ["White"] }, "is_available": false, "unlock": "manual" }, { "id": 2199, "name": "Chantigg Face Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 13, "tags": ["Chantigg", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2200, "name": "Chantigg Cake Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 14, "tags": ["Chantigg", "Food"] }, "is_available": true, "unlock": "purchase" }, { "id": 2201, "name": "Grade A+ Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 0, "tags": ["Pencil", "Sep23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2202, "name": "Globe Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 1, "tags": ["Pencil", "Sep23", "Earth", "Green", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2203, "name": "Nerd Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 15, "tags": ["Pencil", "Sep23", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2204, "name": "Gold Beak Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 13, "tags": ["vipItem", "Premium"] }, "is_available": true, "unlock": "vip", "activeProduct": false, "sku": ["item_hat_golden_wing"] }, { "id": 2205, "name": "Zombie Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 10, "tags": ["Halloween2", "Oct23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2206, "name": "Werewolf Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 9, "tags": ["Halloween2", "Oct23", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 2207, "name": "Vampire Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 8, "tags": ["Halloween2", "Oct23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2208, "name": "Sasquatch Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 7, "tags": ["Halloween2", "Oct23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2209, "name": "Medusa Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 6, "tags": ["Halloween2", "Oct23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2210, "name": "Blue Cyclops Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 5, "tags": ["Halloween2", "Oct23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2211, "name": "Cthulu Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 4, "tags": ["Halloween2", "Oct23", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2212, "name": "Baldwiz Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 3, "tags": ["Halloween2", "Oct23", "Skull"] }, "is_available": false, "unlock": "purchase" }, { "id": 2213, "name": "Fang Pablo Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 11, "tags": ["Halloween2", "Oct23", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2214, "name": "Jack'o'lantern Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 12, "tags": ["Halloween2", "Oct23", "Face", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2215, "name": "Circle Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 0, "tags": ["Egg Game", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2216, "name": "Square Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 15, "tags": ["Egg Game", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2217, "name": "Umbrella Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 1, "tags": ["Egg Game", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2218, "name": "Triangle Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 14, "tags": ["Egg Game", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 2219, "name": "NACL Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 2, "tags": ["League", "Yellow", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 2220, "name": "RBL Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 3, "tags": ["League", "Black", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 2221, "name": "Sheesh Face Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 11 }, "is_available": true, "unlock": "purchase" }, { "id": 2222, "name": "Black Eggs Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 10, "tags": ["Black Fryday"] }, "is_available": false, "unlock": "purchase" }, { "id": 2223, "name": "Black Fries Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 9, "tags": ["Black Fryday"] }, "is_available": false, "unlock": "purchase" }, { "id": 2224, "name": "Red Wins Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 4, "tags": ["KotC", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2225, "name": "Blue Wins Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 5, "tags": ["KotC", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 2226, "name": "I put the OP in Coop Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 6, "tags": ["KotC"] }, "is_available": true, "unlock": "purchase" }, { "id": 2227, "name": "I rule the Roost Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 7, "tags": ["KotC"] }, "is_available": true, "unlock": "purchase" }, { "id": 2228, "name": "2022 Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 12, "tags": ["2022", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2229, "name": "Nervous Elf Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 14, "tags": ["Christmas2", "Face", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2230, "name": "Pro Plays Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 13, "tags": ["Drops", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 2231, "name": "Ganbaru Okan Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 15, "tags": ["Drops", "Black", "Pink"] }, "is_available": false, "unlock": "manual" }, { "id": 2232, "name": "Cold Face Stamp", "price": 1750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 0, "tags": ["Chilly", "Ice"] }, "is_available": false, "unlock": "purchase" }, { "id": 2233, "name": "Snowman Face Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 1, "tags": ["Chilly", "Smile", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2234, "name": "Hockey Sticks Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 2, "tags": ["Chilly", "Brown", "Canada"] }, "is_available": false, "unlock": "purchase" }, { "id": 2235, "name": "Happy Aww Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 3, "tags": ["Kawaii", "Cute", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2236, "name": "Sad Aww Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 4, "tags": ["Kawaii", "Cute", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2237, "name": "Heart Eyes Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 5, "tags": ["Kawaii", "Cute", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2238, "name": "Star Eyes Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 6, "tags": ["Kawaii", "Cute", "Face", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2239, "name": "Shocked Eyes Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 7, "tags": ["Kawaii", "Cute", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2240, "name": "Ecstatic Eyes Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 8, "tags": ["Kawaii", "Cute", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2241, "name": "Pleased Eyes Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 9, "tags": ["Kawaii", "Cute", "Face", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 2242, "name": "Cat Wink Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 10, "tags": ["Kawaii", "Cute", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2243, "name": "Nate's Monies Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 11, "tags": ["Nate", "MayM23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2244, "name": "Nate's Bomb Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 12, "tags": ["Nate", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2245, "name": "Nate's Eel Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 13, "tags": ["Nate", "Oct23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2246, "name": "Nate's Skypunch Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 14, "tags": ["Nate", "MarM23", "Pixel"] }, "is_available": false, "unlock": "purchase" }, { "id": 2247, "name": "Nate's Stonks Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 15, "tags": ["Nate", "Yellow", "Ahh"] }, "is_available": false, "unlock": "purchase" }, { "id": 2248, "name": "Nate's Dead Jason Stamp", "price": 5e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 15, "tags": ["Nate", "Black", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2249, "name": "Nate's Alive Jason Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 14, "tags": ["Nate", "Black", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2250, "name": "Nate's Noodly Appendages Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 13, "tags": ["Nate", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2251, "name": "Phoenix BLZ Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 10, "tags": ["SL", "Orange", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 2252, "name": "Navi Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 9, "tags": ["SL", "Blue", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 2253, "name": "NCR Clan Logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 8, "tags": ["SL", "Black", "Purple"] }, "is_available": false, "unlock": "manual" }, { "id": 2254, "name": "Ukraine Stamp", "price": 100, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 7, "tags": ["UA", "Blue", "Yellow", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 2255, "name": "Nothin' but Net Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 11, "tags": ["Bros", "Basketball"] }, "is_available": false, "unlock": "purchase" }, { "id": 2256, "name": "On Fire Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 12, "tags": ["Bros", "Basketball", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 2257, "name": "Diamonds Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 6, "tags": ["EGGORG", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2258, "name": "Clubs Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 5, "tags": ["EGGORG", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2259, "name": "Spades Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 4, "tags": ["EGGORG", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2260, "name": "Hearts Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 3, "tags": ["EGGORG", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2261, "name": "Egg Org Shield Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 2, "tags": ["EGGORG", "Apr23", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2262, "name": "Polarized Moon Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 1, "tags": ["Relic", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 2263, "name": "Shattered EGG ORG Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 0, "tags": ["Relic", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 2264, "name": "Wizard Neko Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 15, "tags": ["Relic", "Mar23", "AugM23", "Dog"] }, "is_available": false, "unlock": "purchase" }, { "id": 2265, "name": "Jason Eyes Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 14, "tags": ["Relic", "Mar23", "AugM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2266, "name": "Wizard Cheer Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 13, "tags": ["Relic", "Mar23", "AugM23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2267, "name": "Egg Love Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 12, "tags": ["Relic", "Mar23", "AugM23", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 2268, "name": "Going Eggstinct Stamp", "price": 350, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 11, "tags": ["Dino", "May23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2269, "name": "No Tar Pits Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 10, "tags": ["Dino", "May23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2270, "name": "Clutch Up! Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 9, "tags": ["Dino", "May23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2271, "name": "No Meteors Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 8, "tags": ["Dino", "May23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2272, "name": "No Volcanos Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 7, "tags": ["Dino", "May23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2273, "name": "RAWR Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 6, "tags": ["Dino", "MarM23", "Yellow", "Purple"] }, "is_available": false, "unlock": "purchase" }, { "id": 2274, "name": "Baby Dino Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 5, "tags": ["Dino", "May23", "Green", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2275, "name": "Bluetooth Stamp", "price": 1750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 0, "tags": ["Mobile", "JunM23", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2276, "name": "Happy Phone Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 1, "tags": ["Mobile", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2277, "name": "Mad Phone Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 2, "tags": ["Mobile", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2278, "name": "Signal Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 3, "tags": ["Mobile", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 2279, "name": "Charging! Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 4, "tags": ["Mobile", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2280, "name": "Eggy-wan Beard Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 0, "tags": ["Eggwalker2", "Face", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2281, "name": "Control Panel Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 1, "tags": ["Eggwalker2", "Red", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2282, "name": "Evader face Stamp", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 2, "tags": ["Eggwalker2", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2283, "name": "Ladybug Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 3, "tags": ["Summer", "JunM23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2284, "name": "Camper Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 4, "tags": ["Summer", "JunM23", "Green", "Tent"] }, "is_available": false, "unlock": "purchase" }, { "id": 2285, "name": "Oasis Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 5, "tags": ["Summer", "JunM23", "Black", "Red", "Blue", "Tree"] }, "is_available": false, "unlock": "purchase" }, { "id": 2286, "name": "Hot Face Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 6, "tags": ["Summer", "JunM23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 2287, "name": "Sun's out Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 7, "tags": ["Summer", "JunM23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2288, "name": "Blue's #1 Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 8, "tags": ["Sports", "JulyM23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2289, "name": "Red's #1 Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 9, "tags": ["Sports", "JulyM23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2290, "name": "Football Laces Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 10, "tags": ["Sports", "JulyM23", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2291, "name": "Hockey crossed sticks Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 11, "tags": ["Sports", "JulyM23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2292, "name": "Trophy #1 Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 12, "tags": ["Sports", "JulyM23", "Yellow", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 2293, "name": "What's the play? Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 13, "tags": ["Sports", "JulyM23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2294, "name": "Whistle Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 14, "tags": ["Sports", "JulyM23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2295, "name": "Go Team Eggs Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 15, "tags": ["Sports", "JulyM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2296, "name": "GOAL Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 0, "tags": ["Sports", "JulyM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2297, "name": "Cooked Chicken Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 1, "tags": ["Chicken", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2298, "name": "Lil Nugz Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 2, "tags": ["Chicken"] }, "is_available": false, "unlock": "purchase" }, { "id": 2299, "name": "Toast Face Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 3, "tags": ["Breakfast", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2300, "name": "Butter believe it Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 4, "tags": ["Breakfast", "Food", "NovM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2301, "name": "Sour Face Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 5, "tags": ["Breakfast", "July23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2302, "name": "Pancakes Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 6, "tags": ["Breakfast", "Brown", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2303, "name": "Hard Boiled Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 7, "tags": ["Breakfast", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2304, "name": "Coffee makes me happy! Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 8, "tags": ["Breakfast", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2305, "name": "Bacon Bacon Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 9, "tags": ["Breakfast", "Red", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2306, "name": "Scavenger Statue Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 10, "tags": ["Scavenger", "Blue", "Wizard"] }, "is_available": false, "unlock": "purchase" }, { "id": 2307, "name": "Scavenger Map Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 11, "tags": ["Scavenger", "Wizard"] }, "is_available": false, "unlock": "purchase" }, { "id": 2308, "name": "Scavenger Magnifeye Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 12, "tags": ["Scavenger", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2309, "name": "Scavenger Compass Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 13, "tags": ["Scavenger", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2310, "name": "Scavenger Monocle Face Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 14, "tags": ["Scavenger", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2311, "name": "Paint Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 15, "tags": ["Pencil2", "Sep23", "Rainbow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2312, "name": "Science Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 0, "tags": ["Pencil2", "Sep23", "Blue", "Purple", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2313, "name": "Schoolbus Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 1, "tags": ["Pencil2", "Sep23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2314, "name": "Math Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 2, "tags": ["Pencil2", "Sep23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2315, "name": "Sharkbucks Stamp", "price": 6900, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 3, "tags": ["Sep22", "Green", "Face"] }, "is_available": true, "unlock": "purchase" }, { "id": 2316, "name": "Kilzomatic Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 4, "tags": ["Sep22", "Drops3", "Blue", "Eggs"] }, "is_available": false, "unlock": "manual" }, { "id": 2317, "name": "Diablo Sticker Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 5, "tags": ["Sep22", "Mar23", "AugM23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2318, "name": "Pablo Sticker Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 6, "tags": ["Sep22", "Mar23", "AugM23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2319, "name": "The Jaw Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 8, "tags": ["Sep22", "Drops3", "Face", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 2320, "name": "Pablo GG Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 7, "tags": ["Sep22", "Mar23", "AugM23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2321, "name": "Trick Or Treat Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 9, "tags": ["Halloween3", "OctM23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 2322, "name": "Scary Clown Face Stamp", "price": 1990, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 10, "tags": ["Halloween3", "OctM23", "It"] }, "is_available": false, "unlock": "purchase" }, { "id": 2323, "name": "KJDCitsme Jacko Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 14, "tags": ["Halloween3", "OctM23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2324, "name": "KJDCitsme Shock Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 11, "tags": ["Halloween3", "OctM23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2325, "name": "Thee_Owl Breakout Yolk Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 13, "tags": ["Halloween3", "OctM23", "Yellow", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2326, "name": "Thee_Owl Peekout Yolk Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 9, "tags": ["Halloween3", "OctM23", "Yellow", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2327, "name": "Waldoh Scratch Face Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 12, "tags": ["Halloween3", "OctM23", "Face", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2328, "name": "Artshocks Half Asleep Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 10, "tags": ["Halloween3", "OctM23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2329, "name": "Scared Stupid Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 8, "tags": ["Halloween3", "OctM23", "Face", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2330, "name": "One Cluck Man Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 7, "tags": ["Halloween3", "OctM23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2331, "name": "Skullface Kills Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 6, "tags": ["Halloween3", "OctM23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2332, "name": "Witches Broom Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 15, "tags": ["Halloween3", "OctM23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2333, "name": "Fall Leaf Stamp", "price": 200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 11, "tags": ["NovM23", "Thanksgiving", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2334, "name": "Turkey head on Stamp", "price": 400, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 12, "tags": ["NovM23", "Thanksgiving", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2335, "name": "Forest Shroom Stamp", "price": 600, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 13, "tags": ["NovM23", "Thanksgiving2", "Red", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2336, "name": "Apple Core Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 14, "tags": ["NovM23", "Thanksgiving2", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2337, "name": "Drumstick Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 15, "tags": ["NovM23", "Thanksgiving2", "Brown", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2338, "name": "It's Corn Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 4, "tags": ["NovM23", "Thanksgiving2", "Yellow", "Green", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 2339, "name": "Corntastic Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 5, "tags": ["NovM23", "Thanksgiving", "Yellow", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 2340, "name": "You won a 1v1 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 3, "tags": ["Badegg", "Purple", "Blue", "Eggs"] }, "is_available": false, "unlock": "manual" }, { "id": 2341, "name": "Wizard Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 2, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2342, "name": "Reload the clip Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 1, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2343, "name": "Regeneration Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 0, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2344, "name": "Upgrade Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 0, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2345, "name": "Health Drop Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 1, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2346, "name": "Sleeps Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 2, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2347, "name": "Marksman Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 3, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2348, "name": "Restocked Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 4, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2349, "name": "Rambod Face Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 5, "tags": ["Badegg", "Black", "DecM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2350, "name": "Surprise! Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 6, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2351, "name": "Goose Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 7, "tags": ["Badegg", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2352, "name": "New year 2023 Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 8, "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2353, "name": "Mixtape Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 9, "tags": ["Rockstar", "JanM23", "Grey", "Gray", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 2354, "name": "Treble clef Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 10, "tags": ["Rockstar", "JanM23", "Black", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 2355, "name": "Rock on Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 11, "tags": ["Rockstar", "JanM23", "Yellow", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 2356, "name": "Buck Teeth", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 13, "tags": ["Groundhog", "Feb23", "Face", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 2357, "name": "Alarm Clock Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 12, "tags": ["Groundhog", "Newsletter", "Feb23", "White", "Silver", "Feb24"] }, "is_available": false, "unlock": "manual" }, { "id": 2358, "name": "Horseshoe Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 15, "tags": ["farm", "FebM23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2359, "name": "Sunflower Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 14, "tags": ["farm", "FebM23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2360, "name": "CEO Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 0, "tags": ["League", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 2361, "name": "LEV Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 1, "tags": ["League", "Green"] }, "is_available": false, "unlock": "manual" }, { "id": 2362, "name": "RTV Clan Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 2, "tags": ["League", "Blue", "Purple"] }, "is_available": false, "unlock": "manual" }, { "id": 2363, "name": "Shell Tournaments Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 3, "tags": ["League", "Orange"] }, "is_available": true, "unlock": "purchase" }, { "id": 2364, "name": "NPS Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 4, "tags": ["League", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 2365, "name": "Shell Tournaments #1 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 5, "tags": ["League", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 2366, "name": "Hello my name is Pablo Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 6, "tags": ["Drops4", "Mar23", "AugM23", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2367, "name": "Happily Fried Stamp", "price": 300, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 7, "tags": ["Drops4", "Mar23", "AugM23", "White", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2368, "name": "Game Of The Year Stamp", "price": 350, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 8, "tags": ["Drops4", "Mar23", "Yellow", "GOTY"] }, "is_available": false, "unlock": "purchase" }, { "id": 2369, "name": "Wizards on Fire! Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 9, "tags": ["Drops4", "Mar23", "Blue", "BWD"] }, "is_available": false, "unlock": "purchase" }, { "id": 2370, "name": "Banned Aid Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 10, "tags": ["Drops4", "Mar23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2371, "name": "xQc Ape Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 11, "tags": ["Drops4", "Mar23", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 2372, "name": "Shell Shockers Logo Stamp", "price": 50, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 12, "tags": ["Drops4", "Mar23", "Eggs", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2373, "name": "Griffen Chin Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 13, "tags": ["Drops4", "Mar23", "Face", "Black"] }, "is_available": false, "unlock": "manual" }, { "id": 2374, "name": "That's a Fowl Stamp", "price": 150, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 14, "tags": ["Bros", "MarM23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2375, "name": "Stuffed Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 15, "tags": ["Bros", "MarM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2376, "name": "Bear Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 0, "tags": ["Bros", "MarM23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2377, "name": "Tiger Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 1, "tags": ["Bros", "MarM23", "Tiger", "Cat"] }, "is_available": false, "unlock": "purchase" }, { "id": 2378, "name": "Basket Bros Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 2, "tags": ["Bros", "MarM23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 2379, "name": "Hydrate! Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 3, "tags": ["Bros", "MarM23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2380, "name": "Egg Jordan Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 4, "tags": ["Bros", "MarM23", "Black", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2381, "name": "Kiss me I'm Irish Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 5, "tags": ["StPatricksDay", "MarM23", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2382, "name": "Monster Talisman Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 6, "tags": ["Monsters", "Apr23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2383, "name": "Hero Talisman Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 7, "tags": ["Heroes", "Apr23"] }, "is_available": false, "unlock": "purchase" }, { "id": 2384, "name": "Judgement arrow Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 8, "tags": ["Apr23", "Gold", "Green", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2385, "name": "Critical Hit Stamp", "price": 200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 9, "tags": ["Apr23", "Red", "Gold", "D20", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2386, "name": "Breath Weapon Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 10, "tags": ["Apr23", "Red", "Gold", "Dragon"] }, "is_available": false, "unlock": "purchase" }, { "id": 2387, "name": "Egg Org & Eggventure Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 11, "tags": ["Apr23", "Red", "Gold", "Dragon"] }, "is_available": false, "unlock": "purchase" }, { "id": 2388, "name": "Heroes Potion Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 12, "tags": ["Heroes", "Apr23", "Green", "Heart"] }, "is_available": false, "unlock": "manual" }, { "id": 2389, "name": "Monsters Potion Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 13, "tags": ["Apr23", "Monsters", "Red", "Skull"] }, "is_available": false, "unlock": "manual" }, { "id": 2390, "name": "Monobrow Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 14, "tags": ["May23", "Dino2", "Black", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2391, "name": "Slay the Beast Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 15, "tags": ["May23", "Dino2", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2392, "name": "Caveman Classic Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 0, "tags": ["May23", "Dino2", "Face", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 2393, "name": "Stone Tools Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 1, "tags": ["May23", "Dino2", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2394, "name": "Chart Stamp", "price": 10, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 3, "tags": ["MayM23", "Eggflation", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2395, "name": "Money Tree Stamp", "price": 100, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 4, "tags": ["MayM23", "Eggflation", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 2396, "name": "Eggflation Rollercoaster Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 2, "tags": ["MayM23", "Eggflation", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 2397, "name": "HODL Stamp", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 5, "tags": ["MayM23", "Eggflation"] }, "is_available": true, "unlock": "purchase" }, { "id": 2398, "name": "Polaroid Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 6, "tags": ["Jun23", "Photo", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2399, "name": "Wedding Crasher Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 7, "tags": ["Jun23", "Photo", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2400, "name": "Apature Stamp", "price": 825, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 8, "tags": ["Jun23", "Photo", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 2401, "name": "Dour Mustache Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 9, "tags": ["Jun23", "Photo", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2402, "name": "Starfish Stamp", "price": 505, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 10, "tags": ["JunM23", "Summer2", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2403, "name": "Jellyfish Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 11, "tags": ["JunM23", "Summer2", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2404, "name": "Beach Vibes Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 12, "tags": ["JunM23", "Summer2"] }, "is_available": false, "unlock": "purchase" }, { "id": 2405, "name": "Beach Ball Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 13, "tags": ["JunM23", "Summer2", "White", "Blue", "Yellow", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2406, "name": "Equinox Sun Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 0, "tags": ["July23", "Equinox", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2407, "name": "Equinox Moon Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 1, "tags": ["July23", "Equinox", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 2408, "name": "Equinox YinYang Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 14, "tags": ["July23", "Equinox", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2409, "name": "Pablodala Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 15, "tags": ["July23", "Equinox", "Mandala", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2410, "name": "Star Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 2, "tags": ["JulyM23", "Sports2"] }, "is_available": false, "unlock": "purchase" }, { "id": 2411, "name": "Grind Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 4, "tags": ["JulyM23", "Sports2", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 2412, "name": "Fellow Kids Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 3, "tags": ["JulyM23", "Sports2", "Red", "Skateboard"] }, "is_available": false, "unlock": "purchase" }, { "id": 2413, "name": "Safety Team Approved Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 5, "tags": ["JulyM23", "Sports2"] }, "is_available": false, "unlock": "purchase" }, { "id": 2414, "name": "The MenoXD Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 6, "tags": ["JulyM23", "Red", "xd"] }, "is_available": true, "unlock": "purchase" }, { "id": 2415, "name": "Red S-tier Racing Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 7, "tags": ["Aug23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2416, "name": "Green S-tier Racing Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 8, "tags": ["Aug23", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 2417, "name": "Question block Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 9, "tags": ["Aug23", "Yellow", "?", "JanM24"] }, "is_available": false, "unlock": "purchase" }, { "id": 2418, "name": "Racing Flags Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 10, "tags": ["Aug23", "Black", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2419, "name": "Stopwatch Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 11, "tags": ["Newsletter", "Aug23", "White", "Clock"] }, "is_available": false, "unlock": "manual" }, { "id": 2420, "name": "Shy Egg Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 12, "tags": ["Aug23", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2421, "name": "Banana Peel Stamp", "price": 1200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 13, "tags": ["Aug23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2422, "name": "Respawn Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 14, "tags": ["Aug23", "Mushroom", "Green", "1up"] }, "is_available": false, "unlock": "purchase" }, { "id": 2423, "name": "Om Nom Stamp", "price": 200, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 27, "y": 15, "tags": ["AugM23", "Drops5", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2424, "name": "Harrison Cat Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 0, "tags": ["AugM23", "Drops5", "Thumb", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2425, "name": "Flushed Face Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 1, "tags": ["AugM23", "Drops5"] }, "is_available": false, "unlock": "purchase" }, { "id": 2426, "name": "Albino Snake Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 2, "tags": ["AugM23", "Drops5", "Grey", "Gray", "ABHS"] }, "is_available": false, "unlock": "manual" }, { "id": 2427, "name": "Shell Wiki Stamp", "price": 3210, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 3, "tags": ["AugM23", "Drops5", "Egg", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 2428, "name": "Wiz Ears Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 4, "tags": ["AugM23", "Drops5", "Blue", "BWD"] }, "is_available": false, "unlock": "purchase" }, { "id": 2429, "name": "r/place Pablo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 5, "tags": ["AugM23", "Drops5", "Yellow", "Orange", "Smile"] }, "is_available": false, "unlock": "manual" }, { "id": 2430, "name": "r/place BWD skull Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 6, "tags": ["AugM23", "Drops5", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 2431, "name": "r/place BWD logo Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 7, "tags": ["AugM23", "Drops5", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 2432, "name": "Solve for X Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 8, "tags": ["Sep23", "Pencil3", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 2433, "name": "Anarchy Academy", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 9, "tags": ["Sep23", "Pencil3", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2434, "name": "Egg-lectrons Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 10, "tags": ["Sep23", "Pencil3", "Science", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 2435, "name": "Blue Wizard Wrestling Federation Logo", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 12, "tags": ["SepM23", "WBs", "Wrestle", "BWD", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2436, "name": "Bron Lester Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 13, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2437, "name": "Jan Seeya Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 14, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2438, "name": "Rocky Star Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 15, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2439, "name": "Brogan Paw Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 0, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2440, "name": "Romeo Rain Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 1, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2441, "name": "Nacho Mann Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 2, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2442, "name": "Death Brawlin Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 3, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2443, "name": "Bulk Logan Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 4, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2444, "name": "Ray Mystery Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 5, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2445, "name": "Binky Flinch Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 6, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2446, "name": "Bonka Beware Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 7, "tags": ["SepM23", "WBs", "Wrestle"] }, "is_available": false, "unlock": "purchase" }, { "id": 2447, "name": "Wrestlebros 1v1 Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 28, "y": 11, "tags": ["SepM23", "WBs", "Blue", "Purple"] }, "is_available": false, "unlock": "manual" }, { "id": 2448, "name": "Rotting Zombie Fish Stamp", "price": 1750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 8, "tags": ["Oct23", "Halloween4", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2449, "name": "Shark Chomp Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 9, "tags": ["Oct23", "Halloween4", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 2450, "name": "Squiddy Friend Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 10, "tags": ["Oct23", "Halloween4", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 2451, "name": "Venomous Sea Snake Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 11, "tags": ["Oct23", "Halloween4", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2452, "name": "Bait Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 12, "tags": ["Oct23", "Halloween4", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 2453, "name": "Wilson. Wilson... WILSON!", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 13, "tags": ["Oct23", "Halloween4", "Red", "Hand"] }, "is_available": false, "unlock": "purchase" }, { "id": 2454, "name": "Demonic Face Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 14, "tags": ["Oct23", "Face"] }, "is_available": false, "unlock": "manual" }, { "id": 2455, "name": "Boo Crew Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 29, "y": 15, "tags": ["OctM23", "Text", "Purple"] }, "is_available": false, "unlock": "purchase" }, { "id": 2456, "name": "Cool Maid Face", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 0, "tags": ["OctM23", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 2457, "name": "Ghoul Power Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 1, "tags": ["OctM23", "Text", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 2458, "name": "Ghost Malone", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 2, "tags": ["OctM23", "Meme", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2459, "name": "Seen too much Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 3, "tags": ["OctM23", "Purple"] }, "is_available": false, "unlock": "purchase" }, { "id": 2460, "name": "Pumpkin Wizard Digital", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 4, "tags": ["OctM23", "Orange", "BWD", "Infinite Smasher"] }, "is_available": false, "unlock": "purchase" }, { "id": 2461, "name": "Get Ghosted Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 5, "tags": ["OctM23", "Black", "Ghost", "Text"] }, "is_available": false, "unlock": "purchase" }, { "id": 2462, "name": "Sacred Sun Stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 6, "tags": ["Nov23", "Mayan", "Calendar", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2463, "name": "Sea to Sun Totem Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 7, "tags": ["Nov23", "Mayan", "Red", "Orange", "Blue", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 2464, "name": "Ancient Skull Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 8, "tags": ["Nov23", "Mayan", "Bone", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 2465, "name": "Snake Deity Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 9, "tags": ["Nov23", "Mayan", "Green", "Snek"] }, "is_available": false, "unlock": "purchase" }, { "id": 2466, "name": "Raven Lord Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 10, "tags": ["Nov23", "Mayan", "Black", "Nevermore"] }, "is_available": false, "unlock": "purchase" }, { "id": 2467, "name": "Tepey\xF3llotl Stamp", "price": 5e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 11, "tags": ["Nov23", "Mayan", "Leopard", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 2468, "name": "Give Thanksing Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 12, "tags": ["NovM23", "Text", "Thanksgiving3", "Orange", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 2469, "name": "Football Turkey Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 13, "tags": ["NovM23", "Thanksgiving3", "Brown", "Basted"] }, "is_available": false, "unlock": "purchase" }, { "id": 2470, "name": "Basted Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 14, "tags": ["NovM23", "Thanksgiving3", "Yellow", "Text"] }, "is_available": false, "unlock": "purchase" }, { "id": 2471, "name": "Feast Mode Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 30, "y": 15, "tags": ["NovM23", "Thanksgiving3", "Red", "Text"] }, "is_available": false, "unlock": "purchase" }, { "id": 2472, "name": "HoHoHo Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 3, "tags": ["Dec23", "Christmas3", "Red", "Green", "Text"] }, "is_available": false, "unlock": "purchase" }, { "id": 2473, "name": "Nice Egg Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 1, "tags": ["Dec23", "Christmas3", "Red", "Green", "Text"] }, "is_available": false, "unlock": "purchase" }, { "id": 2474, "name": "Naughty Egg Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 0, "tags": ["Dec23", "Christmas3", "Pink", "Purple", "Text"] }, "is_available": false, "unlock": "purchase" }, { "id": 2475, "name": "Big Baubles Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 2, "tags": ["Dec23", "Christmas3", "Red", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 2476, "name": "2024 Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 6, "tags": ["NewYears", "DecM23", "2024", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2477, "name": "Out with the Old", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 4, "tags": ["NewYears", "DecM23", "2024", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2478, "name": "In with the New", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 5, "tags": ["NewYears", "DecM23", "2024", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 2479, "name": "Yolk Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 8, "tags": ["JanM24", "Text", "Racer", "Grey", "Gray", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2480, "name": "Crown Stamp", "price": 25e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 9, "tags": ["JanM24", "Winner", "Racer", "Gold", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2481, "name": "Stop Healing Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 10, "tags": ["JanM24", "Winner", "Racer"] }, "is_available": true, "unlock": "purchase" }, { "id": 2482, "name": "Chinese Egg Stamp", "price": 2500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 11, "tags": ["JanM24", "Purple", "Yellow", "Text", "Racer"] }, "is_available": true, "unlock": "purchase" }, { "id": 2483, "name": "Pireggi Logo", "price": 1e4, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 7, "tags": ["JanM24", "Text", "Black", "Pireggi"] }, "is_available": true, "unlock": "purchase" }, { "id": 2484, "name": "Deez Acorns", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 12, "tags": ["Feb24", "Nuts", "Nutz", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2485, "name": "Cute Bear Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 13, "tags": ["Feb24", "Tongue", "Face", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2486, "name": "Truth or Deer Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 14, "tags": ["Feb24", "Text", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2487, "name": "Cute Owl Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 31, "y": 15, "tags": ["Feb24", "Face", "Who", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 2488, "name": "Cupid Squee Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 0, "y": 16, "tags": ["Feb24", "Pink", "Red", "Face"] }, "is_available": false, "unlock": "manual" }, { "id": 2489, "name": "Kyler Bappy", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 1, "y": 16, "tags": ["FebM24", "Player", "Face", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2490, "name": "Nay Moore", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 2, "y": 16, "tags": ["FebM24", "Player", "Face", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2491, "name": "Davey Bendem", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 3, "y": 16, "tags": ["FebM24", "Player", "Face", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2492, "name": "Meggy Repo", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 4, "y": 16, "tags": ["FebM24", "Player", "Face", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2493, "name": "Lion Messy", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 5, "y": 16, "tags": ["FebM24", "Player", "Face", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2494, "name": "Chris Ronald", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 6, "y": 16, "tags": ["FebM24", "Player", "Face", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2495, "name": "SUUIII", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 7, "y": 16, "tags": ["FebM24", "Player", "Face", "Blue", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2496, "name": "Red Card!", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 8, "y": 16, "tags": ["FebM24", "Foul", "Penalty", "Red", "Sbros"] }, "is_available": false, "unlock": "purchase" }, { "id": 2497, "name": "Triskelion Stamp", "price": 2e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 9, "y": 16, "tags": ["Mar24", "StPatricksDay", "Irish", "Celtic", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2498, "name": "Negative Ward Stamp", "price": 1500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 10, "y": 16, "tags": ["StPatricksDay", "Irish", "Celtic", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2499, "name": "Celtic Knot Stamp", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 11, "y": 16, "tags": ["StPatricksDay", "Irish", "Celtic", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2500, "name": "Bad Bunny Patch", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 17, "y": 16, "tags": ["Mar24", "Rabbit", "Fur", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 2501, "name": "Triquetra Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 13, "y": 16, "tags": ["StPatricksDay", "Irish", "Celtic", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2502, "name": "Finest Emeralds", "price": 5e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 14, "y": 16, "tags": ["StPatricksDay", "Irish", "Celtic", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2503, "name": "Lucky Horseshoe Stamp", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 15, "y": 16, "tags": ["StPatricksDay", "Irish", "Celtic", "Green", "Gold", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 2504, "name": "Gang Stamp", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 16, "y": 16, "tags": ["Clan", "Mar24"] }, "is_available": false, "unlock": "manual" }, { "id": 2505, "name": "Wooly Beard", "price": 2147483647, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 12, "y": 16, "tags": ["Future"] }, "is_available": false, "unlock": "manual" }, { "id": 2506, "name": "Jelly Beanz!", "price": 1e3, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 18, "y": 16, "tags": ["MarM24", "Easter", "Food", "Rainbow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2507, "name": "Jelly Belly Stamp", "price": 500, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 19, "y": 16, "tags": ["MarM24", "Easter", "Food", "Rainbow"] }, "is_available": true, "unlock": "purchase" }, { "id": 2508, "name": "Chocolate Egg", "price": 250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 20, "y": 16, "tags": ["MarM24", "Easter", "Food", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 2509, "name": "Candy Coma Bunny Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 21, "y": 16, "tags": ["MarM24", "Easter", "Food", "Rabbit", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 2510, "name": "Outta Chocolate Stamp", "price": 750, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 22, "y": 16, "tags": ["MarM24", "Easter", "Food", "Rabbit", "Face", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 2511, "name": "E&E stamp", "price": 1250, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 23, "y": 16, "tags": ["MarM24", "Easter", "Text", "Food", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 2512, "name": "Recycled Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 24, "y": 16, "tags": ["MarM24", "Default", "Green", "Symbol"] }, "is_available": true, "unlock": "default" }, { "id": 2513, "name": "Yum Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 25, "y": 16, "tags": ["MarM24", "Default", "Emoji", "Tongue", "Yellow"] }, "is_available": true, "unlock": "default" }, { "id": 2514, "name": "Moai Stamp", "price": 0, "item_type_id": 2, "item_type_name": "Stamp", "category_name": "Stamps", "exclusive_for_class": null, "item_data": { "x": 26, "y": 16, "tags": ["MarM24", "Default", "Emoji", "Easter", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "default" }, { "id": 3100, "name": "The Eggk-47", "price": 0, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47", "tags": ["default", "Blue", "Purple"] }, "is_available": true, "unlock": "default" }, { "id": 3101, "name": "GOLD Eggk-47", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 3102, "name": "Happy Bear Eggk-47", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 3103, "name": "Halloween Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 3104, "name": "Thanksgiving Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 3105, "name": "Christmas Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3106, "name": "New Year 2019 Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_NewYear", "tags": ["NewYears", "2019", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3107, "name": "Groundhog Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 3108, "name": "Buck Rogers Eggk-47", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 3109, "name": "Valentines Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 3110, "name": "St Patricks Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Black", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3111, "name": "Easter Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Easter", "tags": ["Easter", "Red", "Eggs", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3112, "name": "Flame Eggk-47", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Flames", "tags": ["Promotional", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 3113, "name": "Rainbow Eggk-47", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Rainbow", "tags": ["Rainbow", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 3114, "name": "Steampunk Eggk-47", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 3115, "name": "Memphis Eggk-47", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Memphis", "tags": ["Memphis", "Blue", "Orange", "Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 3116, "name": "Eggwalker Eggk-47", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_spaceEgg", "tags": ["Eggwalker", "July23", "Black", "Red", "Grey", "Gray", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3117, "name": "Nuke Zone Eggk-47", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_NukeZone", "tags": ["NukeZone", "Black", "Neon", "Pink"] }, "is_available": true, "unlock": "purchase" }, { "id": 3118, "name": "New Year 2020 Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_NewYear2020", "tags": ["NewYears", "2020", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 3119, "name": "Country Singer Eggk-47", "price": 1e5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 3120, "name": "Albino Eggk-47", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_SnakeAlbino", "tags": ["EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 3121, "name": "Raid Land Eggk-47", "price": 6500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_RaidLand", "tags": ["RaidLand", "Blue", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 3122, "name": "Toxic Eggk-47", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3123, "name": "Music Eggk-47", "price": 8e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Music", "tags": ["Rockstar", "JanM23", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 3124, "name": "Galeggsy Eggk-47", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 3125, "name": "Chicken Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3126, "name": "Techno Eggk-47", "price": 10, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Techno", "tags": ["Dec23", "Blue", "Yellow", "Black", "Pog"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["gun_eggk47_techno"] }, { "id": 3127, "name": "New Year 2021 Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_NewYear2021", "tags": ["NewYears", "2021", "Pink", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3128, "name": "Car Eggk-47", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_car", "tags": ["Cars", "Trains", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 3129, "name": "Merc Zone Eggk-47", "price": 7e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Merc", "tags": ["Merc", "Suit", "Black", "Tie", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 3130, "name": "Summer Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3131, "name": "Pencil Eggk-47", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Pencil", "tags": ["Pencil", "Sep23", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3132, "name": "New Year 2022 Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 3133, "name": "Cards Eggk-47", "price": 1520, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 3134, "name": "Retro Eggk-47", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Retro", "tags": ["Retro", "Pixel", "FebM23", "Blue", "Purple", "Wings", "DecM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_ak_retro"] }, { "id": 3135, "name": "Dino Eggk-47", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Dino", "tags": ["Dino", "May23", "Red", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 3136, "name": "Valkyrie Eggk-47", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Valkyrie", "tags": ["Premium", "Valkyrie", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_ak_valkyrie"] }, { "id": 3137, "name": "Eggwalker Alt Eggk-47", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 3138, "name": "SPORTS Eggk-47", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Sports", "tags": ["Sports", "JulyM23", "Brown", "Orange", "Cricket", "Bat"] }, "is_available": false, "unlock": "purchase" }, { "id": 3139, "name": "Breakfast Eggk-47", "price": 1500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Breakfast", "tags": ["Breakfast", "Food", "Brown", "Syrup", "Waffles"] }, "is_available": false, "unlock": "purchase" }, { "id": 3140, "name": "New Year 2023 Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3141, "name": "Farm Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Farm", "tags": ["Farm", "FebM23", "Food", "Orange", "Green", "Carrot"] }, "is_available": false, "unlock": "purchase" }, { "id": 3142, "name": "Fusion Eggk-47", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Fusion", "tags": ["Premium", "fusion", "FebM23", "White", "Blue", "Grey", "Gray"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_ak47_fusion"] }, { "id": 3143, "name": "Hero Eggk-47", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Fantasy", "tags": ["Heroes", "Apr23", "Sword", "Silver"] }, "is_available": false, "unlock": "purchase" }, { "id": 3144, "name": "Monster Eggk-47", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_FantasyEvil", "tags": ["Monsters", "Apr23", "Purple", "Sword"] }, "is_available": false, "unlock": "purchase" }, { "id": 3145, "name": "Equinox Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 3146, "name": "Paintball Eggk-47", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Paintball", "tags": ["Sports2", "JulyM23", "Grey", "Gray", "Yellow", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3147, "name": "Kart Eggk-47", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Kart", "tags": ["Kart", "Aug23", "Blue", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3148, "name": "BWD Eggk-47", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Wizard", "tags": ["Drops5", "AugM23", "Blue", "Brown", "Crystal"] }, "is_available": false, "unlock": "manual" }, { "id": 3149, "name": "Infernal Eggk-47", "price": 4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Infernal", "tags": ["OctM23", "Infernal", "Black", "Orange", "Red", "Grey", "Gray", "Burn"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_ak_infernal"] }, { "id": 3150, "name": "Ancient Eggk-47", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3151, "name": "Holideggs Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3152, "name": "2024 Eggk-47", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_NewYear2024", "tags": ["DecM23", "NewYears", "2024", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3153, "name": "Racer Eggk-47", "price": 25e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3154, "name": "Chocolate Eggk-47", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Soldier Primary Weapons", "exclusive_for_class": 0, "item_data": { "meshName": "gun_eggk47_Chocolate", "tags": ["MarM24", "Brown", "Gold"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_ak_choc"] }, { "id": 3400, "name": "The Free Ranger", "price": 0, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1", "tags": ["default", "Orange", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "default" }, { "id": 3401, "name": "GOLD Free Ranger", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 3402, "name": "Happy Bear Free Ranger", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 3403, "name": "Halloween Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 3404, "name": "Thanksgiving Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 3405, "name": "Christmas Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3406, "name": "New Year 2019 Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_NewYear", "tags": ["NewYears", "2019", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3407, "name": "Groundhog Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 3408, "name": "Buck Rogers Free Ranger", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 3409, "name": "Valentines Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 3410, "name": "St Patricks Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Black", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3411, "name": "Easter Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Easter", "tags": ["Easter", "Blue", "Eggs", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3412, "name": "Flame Free Ranger", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Flames", "tags": ["Promotional", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 3413, "name": "Rainbow Free Ranger", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Rainbow", "tags": ["Rainbow", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 3414, "name": "Steampunk Free Ranger", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 3415, "name": "Memphis Free Ranger", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Memphis", "tags": ["Memphis", "Blue", "Orange", "Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 3416, "name": "Eggwalker Free Ranger", "price": 3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_spaceEgg", "tags": ["sale", "Eggwalker", "July23", "Black", "Grey", "Gray", "Yellow", "MarM24", "premFeatTwo"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_csg1_space"] }, { "id": 3417, "name": "Nuke Zone Free Ranger", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_NukeZone", "tags": ["NukeZone", "Yellow", "Black", "Neon"] }, "is_available": true, "unlock": "purchase" }, { "id": 3418, "name": "New Year 2020 Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_NewYear2020", "tags": ["NewYears", "2020", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 3419, "name": "Country Singer Free Ranger", "price": 1e5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 3420, "name": "Albino Free Ranger", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_SnakeAlbino", "tags": ["EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 3421, "name": "Raid Land Free Ranger", "price": 6500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_RaidLand", "tags": ["RaidLand", "Blue", "Yellow", "Brown", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 3422, "name": "Toxic Free Ranger", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3423, "name": "Music Free Ranger", "price": 8e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Music", "tags": ["Rockstar", "JanM23", "Black", "Guitar"] }, "is_available": false, "unlock": "purchase" }, { "id": 3424, "name": "Galeggsy Free Ranger", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 3425, "name": "Chicken Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3426, "name": "Techno Free Ranger", "price": 10, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Techno", "tags": ["Premium", "Techno", "Cats", "Catz", "Purple", "Yellow", "Black"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gun_csg1_techno"] }, { "id": 3427, "name": "New Year 2021 Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_NewYear2021", "tags": ["NewYears", "2021", "Pink", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3428, "name": "Car Free Ranger", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_car", "tags": ["Cars", "Trains", "Red", "Firetruck"] }, "is_available": true, "unlock": "purchase" }, { "id": 3429, "name": "Merc Zone Free Ranger", "price": 7e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Merc", "tags": ["Merc", "Suit", "Black", "Tie", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 3430, "name": "Summer Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3431, "name": "Retro Free Ranger", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Retro", "tags": ["Retro", "Premium", "Pixel", "Green", "Wings", "JanM24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_csg1_retro"] }, { "id": 3432, "name": "Pencil Free Ranger", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Pencil", "tags": ["Pencil", "Sep23", "Yellow", "Paintbrush"] }, "is_available": false, "unlock": "purchase" }, { "id": 3433, "name": "New Year 2022 Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 3434, "name": "BWD Free Ranger", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Wizard", "tags": ["Drops", "Blue", "Brown", "Crystal"] }, "is_available": false, "unlock": "manual" }, { "id": 3435, "name": "Cards Free Ranger", "price": 1520, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 3436, "name": "Dino Free Ranger", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Dino", "tags": ["Dino", "May23", "Green", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 3437, "name": "Eggpire Free Ranger", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3438, "name": "SPORTS Free Ranger", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Sports", "tags": ["Sports", "JulyM23", "Brown", "White", "Baseball"] }, "is_available": false, "unlock": "purchase" }, { "id": 3439, "name": "Rubber Chicken Free Ranger", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_RubberChicken", "tags": ["Aug23", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_csg1_rubchick"] }, { "id": 3440, "name": "Breakfast Free Ranger", "price": 1500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Breakfast", "tags": ["Breakfast", "Food", "Toast", "Brown", "Eggs", "Bread"] }, "is_available": false, "unlock": "purchase" }, { "id": 3441, "name": "Valkyrie Free Ranger", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Valkyrie", "tags": ["Valkyrie", "Premium", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_range_valk"] }, { "id": 3442, "name": "New Year 2023 Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3443, "name": "Fusion Free Ranger", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Fusion", "tags": ["Premium", "JanM23", "White", "Blue", "Grey", "Gray"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_csg1_fusion"] }, { "id": 3444, "name": "Farm Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Farm", "tags": ["Farm", "FebM23", "Food", "Yellow", "Green", "Corn"] }, "is_available": false, "unlock": "purchase" }, { "id": 3445, "name": "Shellpreme Free Ranger", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Shellpreme", "tags": ["MayM23", "Eggflation", "Premium", "Red"] }, "is_available": true, "unlock": "premium", "activeProduct": false, "sku": ["item_csg1_shellpreme"] }, { "id": 3446, "name": "Equinox Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 3447, "name": "Kart Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Kart", "tags": ["Aug23", "Kart", "Red", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3448, "name": "lifeofnurse Free Ranger", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Nurse", "tags": ["AugM23", "Drops5", "Blue", "Purple", "Heart"] }, "is_available": false, "unlock": "manual" }, { "id": 3449, "name": "Bone Free Ranger", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Bones", "tags": ["OctM23", "Halloween4", "Bone", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3450, "name": "Ancient Free Ranger", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3451, "name": "Holideggs Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3452, "name": "2024 Free Ranger", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_NewYear2024", "tags": ["DecM23", "2024", "NewYears", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3453, "name": "Sleigh Free Ranger", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Christmas", "tags": ["DecM23", "Newsletter", "Gold", "Green", "Red"] }, "is_available": false, "unlock": "manual" }, { "id": 3454, "name": "Racer Free Ranger", "price": 25e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3455, "name": "Infernal Free Ranger", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Ranger Primary Weapons", "exclusive_for_class": 2, "item_data": { "meshName": "gun_csg1_Infernal", "tags": ["JanM24", "Infernal", "Black", "Orange", "Red", "Grey", "Gray", "Burn"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_csg1_infernal"] }, { "id": 3600, "name": "The Scrambler", "price": 0, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge", "tags": ["default", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "default" }, { "id": 3601, "name": "GOLD Scrambler", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 3602, "name": "Happy Bear Scrambler ", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 3603, "name": "Halloween Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 3604, "name": "Thanksgiving Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 3605, "name": "Christmas Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3606, "name": "New Year 2019 Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_NewYear", "tags": ["NewYears", "2019", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3607, "name": "Groundhog Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 3608, "name": "Buck Rogers Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 3609, "name": "Valentines Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 3610, "name": "St Patricks Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Black", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3611, "name": "Easter Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Easter", "tags": ["Easter", "Yellow", "Green", "Eggs", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3612, "name": "Flame Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Flames", "tags": ["Promotional", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 3613, "name": "Rainbow Scrambler", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Rainbow", "tags": ["Rainbow", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 3614, "name": "Steampunk Scrambler", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 3615, "name": "Memphis Scrambler", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Memphis", "tags": ["Memphis", "Yellow", "Green", "Black", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 3616, "name": "Eggwalker Scrambler", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_spaceEgg", "tags": ["Eggwalker", "July23", "Black", "Red", "Grey", "Gray", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3617, "name": "Nuke Zone Scrambler", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_NukeZone", "tags": ["NukeZone", "Black", "Blue", "Neon"] }, "is_available": true, "unlock": "purchase" }, { "id": 3618, "name": "New Year 2020 Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_NewYear2020", "tags": ["NewYears", "2020", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 3619, "name": "Country Singer Scrambler", "price": 1e5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 3620, "name": "Albino Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_SnakeAlbino", "tags": ["EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 3621, "name": "Raid Land Scrambler", "price": 6500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_RaidLand", "tags": ["RaidLand", "Brown", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3622, "name": "Toxic Scrambler", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3623, "name": "Music Scrambler", "price": 8e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Music", "tags": ["Rockstar", "JanM23", "Red", "Gold", "Guitar"] }, "is_available": false, "unlock": "purchase" }, { "id": 3624, "name": "Galeggsy Scrambler", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 3625, "name": "Killstreak Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Killstreak", "tags": ["Killstreak", "Smile", "Yellow", "Brown", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 3626, "name": "Chicken Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3627, "name": "Techno Scrambler", "price": 10, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Techno", "tags": ["Techno", "premium", "SepM23", "Badoosh", "Red", "Purple", "Black"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["gun_gauge_techno"] }, { "id": 3628, "name": "New Year 2021 Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_NewYear2021", "tags": ["NewYears", "2021", "Pink", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3629, "name": "Car Scrambler", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_car", "tags": ["Cars", "Trains", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 3630, "name": "Merc Zone Scrambler", "price": 7e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Merc", "tags": ["Merc", "Suit", "Black", "Tie", "Orange"] }, "is_available": true, "unlock": "purchase" }, { "id": 3631, "name": "Summer Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3632, "name": "Pencil Scrambler", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Pencil", "tags": ["Pencil", "Sep23", "Highlighter"] }, "is_available": false, "unlock": "purchase" }, { "id": 3633, "name": "BWD Fan-art Scrambler", "price": 15e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_BWD", "tags": ["Kids", "Wizard", "Blue", "Rainbow"] }, "is_available": true, "unlock": "purchase" }, { "id": 3634, "name": "Retro Scrambler", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Retro", "tags": ["Retro", "Premium", "Pixel", "Grey", "Gray", "Orange", "Wings", "premFeatOne", "Mar24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_crack_retro"] }, { "id": 3635, "name": "New Year 2022 Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 3636, "name": "Thee_Owl Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_TheeOwl", "tags": ["Relic", "Drops2", "Twitch", "Green", "Fingers"] }, "is_available": false, "unlock": "manual" }, { "id": 3637, "name": "Basket Bros Scrambler", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Basketball", "tags": ["Bros", "JulyM23", "Orange", "Hoops", "FebM24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_bros"] }, { "id": 3638, "name": "Cards Scrambler", "price": 1520, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 3639, "name": "JWBerry3D Scrambler", "price": 75e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_JWBerry", "tags": ["Relic", "Black", "Red", "Glasses"] }, "is_available": true, "unlock": "purchase" }, { "id": 3640, "name": "Dino Scrambler", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Dino", "tags": ["Dino", "May23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3641, "name": "Eggpire Scrambler", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3642, "name": "Valkyrie Scrambler", "price": 3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Valkyrie", "tags": ["Eggwalker2", "Premium", "Valkyrie", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gauge_valk"] }, { "id": 3643, "name": "SPORTS Scrambler", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Sports", "tags": ["Sports", "JulyM23", "Black", "White", "Green", "Soccer", "Football", "FebM24"] }, "is_available": false, "unlock": "purchase" }, { "id": 3644, "name": "Breakfast Scrambler", "price": 1500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Breakfast", "tags": ["Breakfast", "Food", "Red", "Ketchup"] }, "is_available": false, "unlock": "purchase" }, { "id": 3645, "name": "Sharkbucks Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Sharkbucks", "tags": ["Sep22", "Drops3", "Blue", "Smile"] }, "is_available": false, "unlock": "manual" }, { "id": 3646, "name": "Kilzomatic Scrambler", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Kilzomatic", "tags": ["Sep22", "Blue", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 3647, "name": "Badegg Scrambler", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Badegg", "tags": ["Badegg", "Red", "Yellow", "DecM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 3648, "name": "New Year 2023 Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3649, "name": "Sleigh Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Christmas", "tags": ["Christmas2", "Newsletter", "Red", "White", "Gold", "Sleigh"] }, "is_available": false, "unlock": "manual" }, { "id": 3650, "name": "Octopus Scrambler", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Octopus", "tags": ["JanM23", "Oct23", "Blue", "Pink"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gauge_octopus"] }, { "id": 3651, "name": "Farm Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Farm", "tags": ["Farm", "FebM23", "Food", "Yellow", "Gold", "Wheat"] }, "is_available": false, "unlock": "purchase" }, { "id": 3652, "name": "BWD Scrambler", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Wizard", "tags": ["Drops4", "Mar23", "Blue", "Brown", "Crystal"] }, "is_available": false, "unlock": "manual" }, { "id": 3653, "name": "Green Snake Scrambler", "price": 15e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_SnakePatrick", "tags": ["Mar23", "StPatricksDay", "Snek", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3654, "name": "Beholder Scrambler", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Fantasy", "tags": ["Monsters", "Apr23", "Purple", "Yellow", "Eyes"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gauge_monster"] }, { "id": 3655, "name": "Fusion Scrambler", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Fusion", "tags": ["Premium", "MidM23", "Fusion", "White", "Blue", "Grey", "Gray"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gauge_fusion"] }, { "id": 3656, "name": "Equinox Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 3657, "name": "Kart Scrambler", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Kart", "tags": ["Aug23", "Kart", "Blue", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3658, "name": "Ancient Scrambler", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3659, "name": "Holideggs Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3660, "name": "2024 Scrambler", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_NewYear2024", "tags": ["DecM23", "2024", "NewYears", "White", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3661, "name": "Racer Scrambler", "price": 25e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3662, "name": "Cloudkicker Scrambler", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Clouds", "tags": ["Feb24", "Clouds", "White", "Rainbow"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gauge_cloud"] }, { "id": 3663, "name": "Irish Scrambler", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Scrambler Primary Weapons", "exclusive_for_class": 1, "item_data": { "meshName": "gun_dozenGauge_Irish", "tags": ["Mar24", "StPatricksDay", "Green", "Gold", "Mar24"] }, "is_available": true, "unlock": "premium", "activeProduct": false, "sku": ["item_gauge_irish"] }, { "id": 3e3, "name": "The Cluck 9mm", "price": 0, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm", "tags": ["Red", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "default" }, { "id": 3001, "name": "GOLD Cluck 9mm", "price": 1500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 3002, "name": "Happy Bear Cluck 9mm", "price": 5e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 3003, "name": "Halloween Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 3004, "name": "Thanksgiving Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 3005, "name": "Christmas Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3006, "name": "New Years 2019 Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_NewYear", "tags": ["NewYears", "2019", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3007, "name": "Groundhog Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 3008, "name": "Buck Rogers Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Buck", "tags": ["Promotional", "Gray", "Grey", "Silver"] }, "is_available": false, "unlock": "manual" }, { "id": 3009, "name": "Valentines Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 3010, "name": "St Patricks Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Black", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3011, "name": "Easter Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Easter", "tags": ["Easter", "Pink", "Blue", "Eggs", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3012, "name": "Flame Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Flames", "tags": ["Promotional", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 3013, "name": "Rainbow Cluck 9mm", "price": 1e4, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Rainbow", "tags": ["Rainbow", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 3014, "name": "Steampunk Cluck 9mm", "price": 1e4, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 3015, "name": "Memphis Cluck 9mm", "price": 7500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Memphis", "tags": ["Memphis", "White", "Black", "Pink"] }, "is_available": true, "unlock": "purchase" }, { "id": 3016, "name": "Eggwalker Cluck 9mm", "price": 4, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_spaceEgg", "tags": ["Eggwalker", "July23", "Black", "Red", "Grey", "Gray", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_9mm_space"] }, { "id": 3017, "name": "Nuke Zone Skin Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_NukeZone", "tags": ["NukeZone", "Yellow", "Black", "Neon"] }, "is_available": false, "unlock": "manual" }, { "id": 3018, "name": "New Years 2020 Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_NewYear2020", "tags": ["NewYears", "2020", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 3019, "name": "Country Singer Cluck 9mm", "price": 1e5, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 3020, "name": "Albino Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_SnakeAlbino", "tags": ["EggyCashAlbino", "Snek", "White", "Gray", "Grey", "Red", "ABHS"] }, "is_available": false, "unlock": "manual" }, { "id": 3021, "name": "Raid Land Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_RaidLand", "tags": ["RaidLand", "Newsletter", "Rabbit", "Wabbit", "Heart", "Green", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 3022, "name": "Toxic Cluck 9mm", "price": 7500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3023, "name": "Music Cluck 9mm", "price": 8e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Music", "tags": ["Rockstar", "JanM23", "Grey", "Gray", "Harmonica"] }, "is_available": false, "unlock": "purchase" }, { "id": 3024, "name": "Galeggsy Cluck 9mm", "price": 7500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 3025, "name": "Techno Cluck 9mm", "price": 10, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Techno", "tags": ["AprM23", "Red", "Orange", "Yellow", "Pop", "Black"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gun_9mm_techno"] }, { "id": 3026, "name": "Cubic Castles Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_CubicCastles", "tags": ["CubicCastles", "White", "Black", "Red", "Skull"] }, "is_available": false, "unlock": "manual" }, { "id": 3027, "name": "Chicken Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3028, "name": "New Years 2021 Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_NewYear2021", "tags": ["NewYears", "2021", "Pink", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3029, "name": "Retro Cluck 9mm", "price": 5, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Retro", "tags": ["Retro", "Premium", "Pixel", "Red", "Gray", "Grey", "Silver", "Wings", "OctM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_retro_9mm"] }, { "id": 3030, "name": "Car Cluck 9mm", "price": 7500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_car", "tags": ["Cars", "Trains", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 3031, "name": "Merc Zone Cluck 9mm", "price": 7e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Merc", "tags": ["Merc", "Suit", "Black", "Tie", "Red"] }, "is_available": true, "unlock": "purchase" }, { "id": 3032, "name": "Summer Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3033, "name": "Lyerpald Cluck 9mm", "price": 25e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_lyerpald", "tags": ["Dog", "Grey", "Gray", "Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 3034, "name": "Pencil Cluck 9mm", "price": 1500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Pencil", "tags": ["Pencil", "Sep23", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3035, "name": "Devilish Cluck 9mm", "price": 15e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Devilish", "tags": ["Kids", "Red", "Black", "Purple", "Fork"] }, "is_available": true, "unlock": "purchase" }, { "id": 3036, "name": "Bone Cluck 9mm", "price": 5e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Bones", "tags": ["Halloween2", "Oct23"] }, "is_available": false, "unlock": "purchase" }, { "id": 3037, "name": "New Years 2022 Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 3038, "name": "Sleigh Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Christmas", "tags": ["Christmas2", "Newsletter", "Red", "Yellow", "Green", "Gold", "Sleigh"] }, "is_available": false, "unlock": "manual" }, { "id": 3039, "name": "Cards Cluck 9mm", "price": 1520, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Cards", "tags": ["EGGORG", "Apr23"] }, "is_available": false, "unlock": "purchase" }, { "id": 3040, "name": "BWD Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Wizard", "tags": ["Relic", "Drops2", "Blue", "Brown", "Crystal"] }, "is_available": false, "unlock": "manual" }, { "id": 3041, "name": "Dino Cluck 9mm", "price": 5e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Dino", "tags": ["Dino", "May23", "Brown", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3042, "name": "Eggpire Cluck 9mm", "price": 12500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3043, "name": "SPORTS Cluck 9mm", "price": 2e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Sports", "tags": ["Sports", "JulyM23", "White", "Bowling", "Pin"] }, "is_available": false, "unlock": "purchase" }, { "id": 3044, "name": "Breakfast Cluck 9mm", "price": 1500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Breakfast", "tags": ["Breakfast", "Food", "Apple", "Juice", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 3045, "name": "Valkyrie Cluck 9mm", "price": 5, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Valkyrie", "tags": ["Scavenger", "Premium", "Valkyrie", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_9mm_valk"] }, { "id": 3046, "name": "Protractor Cluck 9mm", "price": 1500, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Protractor", "tags": ["Pencil2", "Sep23", "Grey", "Gray", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 3047, "name": "Badegg Cluck 9mm", "price": 5e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Badegg", "tags": ["Badegg", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3048, "name": "New Year 2023 Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3049, "name": "Aquarius Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Aquarius", "tags": ["Groundhog", "Feb23", "Blue", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 3050, "name": "Cloudkicker Cluck 9mm", "price": 5, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Clouds", "tags": ["Premium", "Feb23", "Clouds", "Rainbow", "White", "Feb24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_9mm_cloud"] }, { "id": 3051, "name": "Farm Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Farm", "tags": ["Farm", "FebM23", "Food", "Red", "Tomato"] }, "is_available": false, "unlock": "purchase" }, { "id": 3052, "name": "Thee_Owl Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_TheeOwl", "tags": ["Drops4", "Mar23", "Twitch", "Green", "Fingers"] }, "is_available": false, "unlock": "manual" }, { "id": 3053, "name": "Merc Zone Final Cluck 9mm", "price": 2147483647, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_MercF", "tags": ["Merc", "Suit", "Black", "Tie"] }, "is_available": false, "unlock": "manual" }, { "id": 3054, "name": "Fusion Cluck 9mm", "price": 5, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Fusion", "tags": ["Premium", "AprM23", "White", "Blue", "Grey", "Gray"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_9mm_fusion"] }, { "id": 3055, "name": "Caught in 4k Cluck 9mm", "price": 5, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Camera", "tags": ["Jun23", "Photo", "Smile", "Meme", "FebM24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_9mm_camera"] }, { "id": 3056, "name": "Equinox Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 3057, "name": "Kart Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Kart", "tags": ["Aug23", "Kart", "Red", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3058, "name": "Infernal Cluck 9mm", "price": 4, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Infernal", "tags": ["MarM24", "Infernal", "Black", "Orange", "Red", "Grey", "Gray", "Burn"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_9mm_infernal"] }, { "id": 3059, "name": "Megaphone Cluck 9mm", "price": 5, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Megaphone", "tags": ["Sep23", "Red", "White", "FebM24"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_9mm_mega"] }, { "id": 3060, "name": "Mouse Cluck 9mm", "price": 1e4, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Mouse", "tags": ["Sep23", "Grey", "Gray", "Yellow", "Cheese"] }, "is_available": false, "unlock": "purchase" }, { "id": 3061, "name": "Ancient Cluck 9mm", "price": 2e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3062, "name": "Holideggs Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3063, "name": "2024 Cluck 9mm", "price": 3e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_NewYear2024", "tags": ["DecM23", "2024", "NewYears", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3064, "name": "Racer Cluck 9mm", "price": 25e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3065, "name": "Soccer Bros Cluck 9mm", "price": 5e3, "item_type_id": 4, "item_type_name": "Secondary", "category_name": "Shared Secondary Weapons", "exclusive_for_class": null, "item_data": { "meshName": "gun_cluck9mm_Soccer", "tags": ["FebM24", "Sports", "Ball", "Black", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3800, "name": "The RPEGG", "price": 0, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg", "tags": ["default", "Yellow", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "default" }, { "id": 3801, "name": "GOLD RPEGG", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 3802, "name": "Happy Bear RPEGG", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 3804, "name": "Thanksgiving RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 3805, "name": "Christmas RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3806, "name": "New Year 2019 RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_NewYear", "tags": ["NewYears", "2019", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3807, "name": "Groundhog RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 3808, "name": "Buck Rogers RPEGG", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 3809, "name": "Valentines RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 3810, "name": "St Patricks RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Black", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3811, "name": "Easter RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Easter", "tags": ["Easter", "Orange", "Eggs", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 3812, "name": "Flame RPEGG", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Flames", "tags": ["Promotional", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 3813, "name": "Rainbow RPEGG", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Rainbow", "tags": ["Rainbow", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 3814, "name": "Steampunk RPEGG", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 3815, "name": "Memphis RPEGG", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Memphis", "tags": ["Memphis", "Black", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 3816, "name": "Halloween Skin RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 3817, "name": "Eggwalker RPEGG", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_spaceEgg", "tags": ["Eggwalker", "July23", "Black", "Red", "Grey", "Gray", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3818, "name": "Nuke Zone RPEGG", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_NukeZone", "tags": ["NukeZone", "Black", "Green", "Neon"] }, "is_available": true, "unlock": "purchase" }, { "id": 3819, "name": "New Year 2020 RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_NewYear2020", "tags": ["NewYears", "2020", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 3820, "name": "Country Singer RPEGG", "price": 1e5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 3821, "name": "Albino RPEGG", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_SnakeAlbino", "tags": ["EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 3822, "name": "Raid Lands RPEGG", "price": 6500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_RaidLand", "tags": ["RaidLand", "Silver", "Grey", "Gray", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3823, "name": "Toxic RPEGG", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 3824, "name": "Music RPEGG", "price": 8e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Music", "tags": ["Rockstar", "JanM23", "Yellow", "Gold", "Tuba"] }, "is_available": false, "unlock": "purchase" }, { "id": 3825, "name": "Galeggsy RPEGG", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 3826, "name": "Chicken RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3827, "name": "New Year 2021 RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_NewYear2021", "tags": ["NewYears", "2021", "Pink", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3828, "name": "Techno RPEGG", "price": 10, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Techno", "tags": ["Techno", "Premium", "JunM23", "Yeet", "Rainbow", "Red", "Yellow", "Green", "Blue", "Purple"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_rpeggTechno"] }, { "id": 3829, "name": "Car RPEGG", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_car", "tags": ["Cars", "Trains", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 3830, "name": "Merc Zone RPEGG", "price": 7e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Merc", "tags": ["Merc", "Suit", "Black", "Tie", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 3831, "name": "Summer RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3832, "name": "Pencil RPEGG", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Pencil", "tags": ["Pencil", "Sep23", "Yellow", "Tape"] }, "is_available": false, "unlock": "purchase" }, { "id": 3833, "name": "Bone RPEGG", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Bones", "tags": ["Halloween2", "Oct23"] }, "is_available": false, "unlock": "purchase" }, { "id": 3834, "name": "New Year 2022 RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 3835, "name": "Retro RPEGG", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Retro", "tags": ["Retro", "Premium", "Pixel", "Mar23", "Green", "Wings"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gun_rpegg_retro"] }, { "id": 3836, "name": "Cards RPEGG", "price": 1520, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 3837, "name": "Dino RPEGG", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Dino", "tags": ["Dino", "May23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 3838, "name": "Eggpire RPEGG", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 3839, "name": "SPORTS RPEGG", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Sports", "tags": ["Sports", "JulyM23", "Brown", "Football"] }, "is_available": false, "unlock": "purchase" }, { "id": 3840, "name": "Breakfast RPEGG", "price": 1500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Breakfast", "tags": ["Breakfast", "Food", "Sausage"] }, "is_available": false, "unlock": "purchase" }, { "id": 3841, "name": "Scavenger RPEGG", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Scavenger", "tags": ["Scavenger", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 3842, "name": "Egg Carton RPEGG", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Eggs", "tags": ["Sep22", "Drops3", "Purple", "Grey", "Gray", "Food"] }, "is_available": false, "unlock": "manual" }, { "id": 3843, "name": "Valkyrie RPEGG", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Valkyrie", "tags": ["Valkyrie", "Premium", "Valkyrie", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_rpegg_valk"] }, { "id": 3844, "name": "Missile Toe RPEGG", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Christmas", "tags": ["Christmas2", "Premium", "Red", "White", "Hohoho"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_rpegg_christ"] }, { "id": 3845, "name": "New Year 2023 RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 3846, "name": "Farm RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Farm", "tags": ["Farm", "FebM23", "Barn", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 3947, "name": "Equinox RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 3948, "name": "MenoXD RPEGG", "price": 75e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Meno", "tags": ["JulyM23", "Red", "Black", "xd"] }, "is_available": true, "unlock": "purchase" }, { "id": 3949, "name": "Kart RPEGG", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Kart", "tags": ["Kart", "Aug23", "Blue", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3950, "name": "Thee_Owl RPEGG", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_TheeOwl", "tags": ["Drops5", "AugM23", "Twitch", "Green", "Fingers"] }, "is_available": false, "unlock": "manual" }, { "id": 3951, "name": "Fusion RPEGG", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Fusion", "tags": ["Oct23", "Premium", "Blue", "White", "Gray", "Grey"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_rpegg_fusion"] }, { "id": 3952, "name": "Skellington RPEGG", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Skeleton", "tags": ["OctM23", "Premium", "Black", "White"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_rpegg_skele"] }, { "id": 3953, "name": "Ancient RPEGG", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 3954, "name": "Holideggs RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 3955, "name": "2024 RPEGG", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_NewYear2024", "tags": ["DecM23", "2024", "NewYears", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 3956, "name": "Racer RPEGG", "price": 25e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Eggsploder Primary Weapons", "exclusive_for_class": 3, "item_data": { "meshName": "gun_rpegg_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 4e3, "name": "The Whipper", "price": 0, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg", "tags": ["default", "Grey", "Gray", "Purple"] }, "is_available": true, "unlock": "default" }, { "id": 4001, "name": "GOLD Whipper", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 4002, "name": "Happy Bear Whipper", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 4003, "name": "Halloween Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 4004, "name": "Thanksgiving Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 4005, "name": "Christmas Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 4006, "name": "New Year 2019 Whipper", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_NewYear", "tags": ["NewYears", "2019", "Blue", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 4007, "name": "Groundhog Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 4008, "name": "Buck Rogers Whipper", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 4009, "name": "Valentines Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 4010, "name": "St Patricks Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Black", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 4011, "name": "Easter Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Easter", "tags": ["Easter", "Eggs", "Purple", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 4012, "name": "Flame Whipper", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Flames", "tags": ["Promotional", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 4013, "name": "Rainbow Whipper", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Rainbow", "tags": ["Rainbow", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 4014, "name": "Steampunk Whipper", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 4015, "name": "Memphis Whipper", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Memphis", "tags": ["Memphis", "White", "Black", "Pink"] }, "is_available": true, "unlock": "purchase" }, { "id": 4016, "name": "Eggwalker Whipper", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_spaceEgg", "tags": ["Eggwalker", "July23", "Black", "Red", "Grey", "Gray", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4017, "name": "Nuke Zone Whipper", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_NukeZone", "tags": ["NukeZone", "Red", "Black", "Neon"] }, "is_available": true, "unlock": "purchase" }, { "id": 4018, "name": "New Year 2020 Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_NewYear2020", "tags": ["NewYears", "2020", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 4019, "name": "Country Singer Whipper", "price": 1e5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 4020, "name": "Albino Whipper", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_SnakeAlbino", "tags": ["EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 4021, "name": "Raid Land Whipper", "price": 6500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_RaidLand", "tags": ["RaidLand", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 4022, "name": "Toxic Whipper", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 4023, "name": "Music Whipper", "price": 8e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Music", "tags": ["Rockstar", "JanM23", "Red", "Orange", "Keytar", "Piano"] }, "is_available": false, "unlock": "purchase" }, { "id": 4024, "name": "Galeggsy Whipper", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 4025, "name": "Chicken Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 4026, "name": "Techno Whipper", "price": 10, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Techno", "tags": ["Techno", "AugM23", "Tuh", "Green", "Blue"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_smg_techno"] }, { "id": 4027, "name": "New Year 2021 Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_NewYear2021", "tags": ["NewYears", "2021", "Pink", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 4028, "name": "Car Whipper", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_car", "tags": ["Cars", "Trains", "Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 4029, "name": "Merc Zone Whipper", "price": 7e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Merc", "tags": ["Merc", "Suit", "Black", "Tie", "Purple"] }, "is_available": true, "unlock": "purchase" }, { "id": 4030, "name": "Summer Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4031, "name": "Pencil Whipper", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Pencil", "tags": ["Pencil", "Sep23", "Yellow", "Crayons"] }, "is_available": false, "unlock": "purchase" }, { "id": 4032, "name": "Retro Whipper", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Retro", "tags": ["Retro", "Nov23", "Pixel", "Purple", "Wings"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_smg_retro"] }, { "id": 4033, "name": "New Year 2022 Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 4034, "name": "Cards Whipper", "price": 1520, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 4035, "name": "Dino Whipper", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Dino", "tags": ["Dino", "May23", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4036, "name": "Eggpire Whipper", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 4037, "name": "SPORTS Whipper", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Sports", "tags": ["Sports", "JulyM23", "Red", "Brown", "Badminton"] }, "is_available": false, "unlock": "purchase" }, { "id": 4038, "name": "Breakfast Whipper", "price": 1500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Breakfast", "tags": ["Breakfast", "Food", "Brown", "Red", "Eggs", "Bacon"] }, "is_available": false, "unlock": "purchase" }, { "id": 4039, "name": "Teggtris Whipper", "price": 1980, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Teggtris", "tags": ["Sep22", "Mar23", "Red", "Orange", "Yellow", "Blue", "Grey", "Gray", "Tetris", "GameBoy"] }, "is_available": false, "unlock": "purchase" }, { "id": 4040, "name": "Turkey-Supreme Whipper", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_SpecialTurkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_smg_turk"] }, { "id": 4041, "name": "New Year 2023 Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4042, "name": "Valkyrie Whipper", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Valkyrie", "tags": ["Premium", "Valkyrie", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_smg_valk"] }, { "id": 4043, "name": "Farm Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Farm", "tags": ["Farm", "FebM23", "Food", "Green", "Peas"] }, "is_available": false, "unlock": "purchase" }, { "id": 4044, "name": "Fusion Whipper", "price": 3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Fusion", "tags": ["Premium", " Fusion", "White", "Blue", "Grey", "Gray"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_smg_fusion"] }, { "id": 4045, "name": "Eggflation Whipper", "price": 8e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Eggflation", "tags": ["Eggflation", "MayM23", "Gold", "Yellow", "Eggs"] }, "is_available": true, "unlock": "purchase" }, { "id": 4046, "name": "Equinox Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 4047, "name": "Kart Whipper", "price": 3500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Kart", "tags": ["Kart", "Aug23", "Pink", "Yellow", "Princess", "Peach"] }, "is_available": false, "unlock": "purchase" }, { "id": 4048, "name": "KJDCitsme Whipper", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_KJ", "tags": ["Drops5", "AugM23", "Pink", "Purple", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 4049, "name": "Wrestlebros Whipper", "price": 3500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Wrestlebros", "tags": ["WBs", "SepM23", "Gold", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 4050, "name": "Ancient Whipper", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 4051, "name": "Holideggs Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 4052, "name": "2024 Whipper", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_NewYear2024", "tags": ["DecM23", "NewYears", "2024", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 4053, "name": "Racer Whipper", "price": 25e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Whipper Primary Weapons", "exclusive_for_class": 4, "item_data": { "meshName": "gun_smg_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 4200, "name": "The Crackshot", "price": 0, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24", "tags": ["default", "Blue", "Grey", "Gray"] }, "is_available": true, "unlock": "default" }, { "id": 4201, "name": "GOLD Crackshot", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 4202, "name": "Happy Bear Crackshot", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 4203, "name": "Halloween Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 4204, "name": "Thanksgiving Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 4205, "name": "Christmas Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 4206, "name": "New Year 2019 Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_NewYear", "tags": ["NewYears", "2019", "Blue", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 4207, "name": "Groundhog Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 4208, "name": "Buck Rogers Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 4209, "name": "Valentines Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 4210, "name": "St Patricks Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Black", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 4211, "name": "Easter Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Easter", "tags": ["Easter", "Eggs", "Green", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 4212, "name": "Flame Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Flames", "tags": ["Promotional", "Red", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 4213, "name": "Rainbow Crackshot", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Rainbow", "tags": ["Rainbow", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 4214, "name": "Steampunk Crackshot", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 4215, "name": "Memphis Crackshot", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Memphis", "tags": ["Memphis", "Yellow", "Black", "White"] }, "is_available": true, "unlock": "purchase" }, { "id": 4216, "name": "Eggwalker Crackshot", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_spaceEgg", "tags": ["Eggwalker", "July23", "Black", "Red", "Grey", "Gray", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4217, "name": "Nuke Zone Crackshot", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_NukeZone", "tags": ["NukeZone", "Black", "Purple", "Neon"] }, "is_available": true, "unlock": "purchase" }, { "id": 4218, "name": "New Year 2020 Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_NewYear2020", "tags": ["NewYears", "2020", "Purple", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 4219, "name": "Country Singer Crackshot", "price": 1e5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 4220, "name": "Albino Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_SnakeAlbino", "tags": ["EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 4221, "name": "Raid Land Crackshot", "price": 6500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_RaidLand", "tags": ["RaidLand", "May23", "Purple", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 4222, "name": "Toxic Crackshot", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 4223, "name": "Techno Crackshot", "price": 10, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Techno", "tags": ["Premium", "MayM23", "Untz", "Pink", "Blue", "Purple"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_m24_techno"] }, { "id": 4224, "name": "Music Crackshot", "price": 8e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Music", "tags": ["Rockstar", "JanM23", "Red", "Guitar"] }, "is_available": false, "unlock": "purchase" }, { "id": 4225, "name": "Galeggsy Crackshot", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 4226, "name": "Chicken Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 4227, "name": "New Year 2021 Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_NewYear2021", "tags": ["NewYears", "2021", "Pink", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 4228, "name": "Car Crackshot", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_car", "tags": ["Cars", "Trains", "Blue", "White", "Limosine"] }, "is_available": true, "unlock": "purchase" }, { "id": 4229, "name": "Retro Crackshot", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Retro", "tags": ["Retro", "Premium", "Pixel", "Blue", "Wings"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gun_m24_retro"] }, { "id": 4230, "name": "Merc Zone Crackshot", "price": 7e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Merc", "tags": ["Merc", "Suit", "Black", "Tie", "Blue", "Teal"] }, "is_available": true, "unlock": "purchase" }, { "id": 4231, "name": "Summer Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4232, "name": "Pencil Crackshot", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Pencil", "tags": ["Pencil", "Sep23", "Yellow", "Stapler"] }, "is_available": false, "unlock": "purchase" }, { "id": 4233, "name": "New Year 2022 Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 4234, "name": "Graysocean Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Graysocean", "tags": ["Drops", "Blue"] }, "is_available": false, "unlock": "manual" }, { "id": 4235, "name": "Cards Crackshot", "price": 1520, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 4236, "name": "Dino Crackshot", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Dino", "tags": ["Dino", "May23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 4237, "name": "Eggpire Crackshot", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 4238, "name": "SPORTS Crackshot", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Sports", "tags": ["Sports", "JulyM23", "Silver", "Golf", "Clubs"] }, "is_available": false, "unlock": "purchase" }, { "id": 4239, "name": "Breakfast Crackshot", "price": 1500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Breakfast", "tags": ["Breakfast", "Food", "Fork", "Red", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 4240, "name": "Scavenger Crackshot", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Scavenger", "tags": ["Scavenger", "Premium", "Black", "White", "OctM23"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_m24_scav"] }, { "id": 4241, "name": "BWD Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Wizard", "tags": ["Sep22", "Drops3", "Blue", "Brown", "Crystal"] }, "is_available": false, "unlock": "manual" }, { "id": 4242, "name": "Valkyrie Crackshot", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Valkyrie", "tags": ["Premium", "Valkyrie", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_m24_valk"] }, { "id": 4243, "name": "New Year 2023 Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4244, "name": "Farm Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Farm", "tags": ["Farm", "FebM23", "Food", "Green", "Asparagus"] }, "is_available": false, "unlock": "purchase" }, { "id": 4245, "name": "MenoXD Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Meno", "tags": ["Drops4", "Mar23", "Red", "Black", "xd"] }, "is_available": false, "unlock": "manual" }, { "id": 4246, "name": "Equinox Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 4247, "name": "Kart Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Kart", "tags": ["Kart", "Aug23", "Red", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 4248, "name": "The Fusion Crackshot", "price": 6, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Fusion", "tags": ["Fusion", "SepM23", "Blue", "White", "Black"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_m24_fusion"] }, { "id": 4249, "name": "The Pablo Rifle", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Badegg", "tags": ["Badegg", "Premium", "Yellow", "Brown", "Grey", "Gray"] }, "is_available": false, "unlock": "premium" }, { "id": 4250, "name": "Ancient Crackshot", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 4251, "name": "Holideggs Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 4252, "name": "2024 Crackshot", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_NewYear2024", "tags": ["DecM23", "NewYears", "2024", "White", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 4253, "name": "Infernal Crackshot", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Infernal", "tags": ["DecM23", "Infernal", "Black", "Orange", "Red", "Grey", "Gray", "Burn"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_m24_infernal"] }, { "id": 4254, "name": "Racer Crackshot", "price": 25e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 4255, "name": "Wooden Grove Crackshot", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "Crackshot Primary Weapons", "exclusive_for_class": 5, "item_data": { "meshName": "gun_m24_Grove", "tags": ["Feb24", "Newsletter", "Wood", "Brown"] }, "is_available": false, "unlock": "manual" }, { "id": 16e3, "name": "Grenade", "price": 0, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade", "tags": ["default", "green"] }, "is_available": true, "unlock": "default" }, { "id": 16001, "name": "GOLD Grenade", "price": 2e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 16002, "name": "Happy Bear Grenade", "price": 5e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 16003, "name": "Rainbow Grenade", "price": 1e4, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Rainbow", "tags": ["boom", "White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 16004, "name": "Steampunk Grenade", "price": 1e4, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Steampunk", "tags": ["Steampunk", "Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 16005, "name": "Memphis Grenade", "price": 7500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Memphis", "tags": ["Memphis", "pink", "blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 16006, "name": "Nuke Zone Grenade", "price": 7500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_NukeZone", "tags": ["NukeZone", "Green", "Black", "Neon"] }, "is_available": true, "unlock": "purchase" }, { "id": 16007, "name": "Country Singer Grenade", "price": 1e5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 16008, "name": "Raid Land Grenade", "price": 6500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_RaidLand", "tags": ["SepM23", "brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 16009, "name": "Toxic Grenade", "price": 7500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 16010, "name": "Albino Grenade", "price": 2147483647, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_SnakeAlbino", "tags": ["countrysinger", "EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 16011, "name": "Holy Hand Grenade", "price": 2147483647, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Holy", "tags": ["Premium", "vipItem", "Blue", "Yellow"], "sound": "grenade_holy", "cell": 3, "smokeColors": "white", "fireColors": "gold" }, "is_available": false, "unlock": "vip", "activeProduct": false, "sku": ["item_hat_golden_wing"] }, { "id": 16012, "name": "Groundhog Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Smile", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 16013, "name": "Corrupted Grenade", "price": 75e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Corrupted", "tags": ["Brown", "Eye"], "sound": "grenade_corrupt", "cell": 4, "smokeColors": "corrupt", "fireColors": "corrupt" }, "is_available": true, "unlock": "purchase" }, { "id": 16014, "name": "Skullnado Grenade", "price": 7, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Skull", "tags": ["SepM23", "OctM23", "White", "Halloween"], "sound": "grenade_skullnado", "cell": 2, "smokeColors": "white" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_skullnado"] }, { "id": 16015, "name": "Saint Patricks Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 16016, "name": "Easter Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Easter", "tags": ["Easter", "Blue", "Pink", "Eggs", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 16017, "name": "Pablo Grenade", "price": 2500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Pablo", "tags": ["Brown", "Yellow", "Hat", "Smile"] }, "is_available": true, "unlock": "purchase" }, { "id": 16018, "name": "Diablo Grenade", "price": 2500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Diablo", "tags": ["EGGORG", "Apr23", "Brown", "Frown"] }, "is_available": false, "unlock": "purchase" }, { "id": 16019, "name": "Unicorn Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Unicorn", "tags": ["FebM23", "Sep23", "Pink"], "sound": "grenade_unicorn", "cell": 1, "smokeColors": "white", "fireColors": "rainbow" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_unicorn"] }, { "id": 16020, "name": "Phone Grenade", "price": 2147483647, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Phone", "tags": ["Mobile", "Fire", "Red"], "sound": "grenade_cellphone", "cell": 5, "smokeColors": "white" }, "is_available": false, "unlock": "manual" }, { "id": 16021, "name": "Merc Zone Grenade", "price": 7e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Merc", "tags": ["Merc", "Suit", "Black", "Tie"] }, "is_available": true, "unlock": "purchase" }, { "id": 16022, "name": "The Coconut Punch", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Coconut", "tags": ["Summer", "JunM23", "Food", "Brown", "Drink", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 16023, "name": "Toilet Paper Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_ToiletPaper", "tags": ["Premium", "AugM23", "Poop", "White"], "sound": "grenade_tp", "cell": 6, "smokeColors": "white" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_toilet_papr"] }, { "id": 16024, "name": "Buck Rogers Grenade", "price": 2147483647, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 16025, "name": "Galeggsy Grenade", "price": 7500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 16026, "name": "ChantiGG Booth Grenade", "price": 1e4, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Booth", "tags": ["Chantigg", "Red", "Phone"] }, "is_available": true, "unlock": "purchase" }, { "id": 16027, "name": "Glitterbomb Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Glitterbomb", "tags": ["Pencil", "Premium", "Pink", "Disco"], "sound": "grenade_glitterbomb", "smokeColors": "white", "fireColors": "gold", "cell": 7 }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_glitterbomb"] }, { "id": 16028, "name": "Apple Grenade", "price": 750, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Apple", "tags": ["Pencil", "Sep23", "Red", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 16029, "name": "Wero Grenade", "price": 1250, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Wero", "tags": ["Wero", "Chicken", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 16030, "name": "Halloween Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Halloween", "tags": ["Halloween", "Oct23", "Pumpkin", "Jack", "Orange", "Smile"] }, "is_available": false, "unlock": "purchase" }, { "id": 16031, "name": "Thanksgiving Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Turkey", "tags": ["NovM23", "Thanksgiving", "Eye", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 16032, "name": "Thermal Detonator Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Thermal", "tags": ["Premium", "JunM23", "Red", "Black"], "sound": "grenade_thermal", "cell": 8, "smokeColors": "thermal", "fireColors": "thermal" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_thermal"] }, { "id": 16033, "name": "Christmas Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Present", "tags": ["Christmas2", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 16034, "name": "Eggs of Legends Grenade", "price": 5e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Crystal", "tags": ["Eggteam", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 16035, "name": "New Year 2022 Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 16036, "name": "Supernova Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Supernova", "tags": ["AprM23", "Rainbow", "White", "JanM24"], "sound": "grenade_supernova", "cell": 9, "smokeColors": "supernova", "fireColors": "thermal" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_supernova"] }, { "id": 16037, "name": "Valentines Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Valentines", "tags": ["Valentines", "Heart", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 16038, "name": "Octopus Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Octopus", "tags": ["May23", "Oct23", "White", "Cute", "Feb24"], "sound": "grenade_octopus", "cell": 10, "smokeColors": "white", "fireColors": "white" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_octopus"] }, { "id": 16039, "name": "Bros Grenade", "price": 2147483647, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_BBros", "tags": ["Premium", "Bros", "Orange"], "sound": "grenade_bbros", "cell": 11, "smokeColors": "white", "fireColors": "white" }, "is_available": false, "unlock": "manual" }, { "id": 16040, "name": "Cards Grenade", "price": 1520, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 16041, "name": "Diablo Frown Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_DiabloCannon", "tags": ["Mar23", "EGGORG", "Blue", "Face"], "sound": "grenade_diablocannon", "cell": 12, "smokeColors": "white", "fireColors": "default" }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gre_diablo"] }, { "id": 16042, "name": "Yoyo Grenade", "price": 2147483647, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Yoyo", "tags": ["Relic", "Drops2", "Blue", "White"] }, "is_available": false, "unlock": "manual" }, { "id": 16043, "name": "Dino Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Dino", "tags": ["Dino", "May23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 16044, "name": "Bumblebee Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Bee", "tags": ["Premium", "Summer", "Mar23", "Yellow", "Black", "Cute"], "sound": "grenade_bees", "cell": 13, "smokeColors": "white", "fireColors": "default" }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gre_bumble"] }, { "id": 16045, "name": "Soccer Grenade", "price": 2500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Soccer", "tags": ["Sports", "JulyM23", "Black", "White", "FebM24"] }, "is_available": false, "unlock": "purchase" }, { "id": 16046, "name": "Football Helmet Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Football", "tags": ["Premium", "Sports", "JulyM23", "Red"], "sound": "grenade_football", "cell": 14, "smokeColors": "softblack", "fireColors": "default" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_football"] }, { "id": 16047, "name": "Unhatched Chicken Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Chicken", "tags": ["Chicken", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 16048, "name": "Valkyrie Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Valkyrie", "tags": ["Premium", "Valkyrie", "Gold", "Yellow", "Blue"], "sound": "grenade_valkyrie", "cell": 15, "smokeColors": "white", "fireColors": "default" }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_valk"] }, { "id": 16049, "name": "Milk Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Milk", "tags": ["Premium", "Breakfast", "MayM23", "Pink", "Food"], "sound": "grenade_milk", "cell": 16, "smokeColors": "white", "fireColors": "default" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_milk"] }, { "id": 16050, "name": "Breakfast Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Breakfast", "tags": ["Breakfast", "Food", "Eggs", "Bacon"] }, "is_available": false, "unlock": "purchase" }, { "id": 16051, "name": "Eyeball Grenade", "price": 5e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Eyeball", "tags": ["Scavenger", "AugM23", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 16052, "name": "Padlock Grenade", "price": 4200, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Padlock", "tags": ["Pencil2", "Sep23", "Grey", "Gray", "Locker"] }, "is_available": false, "unlock": "purchase" }, { "id": 16053, "name": "Barrel Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Barrel", "tags": ["Sep22", "Mar23", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 16054, "name": "Bloodonade Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_premium_Blood", "tags": ["Premium", "Halloween3", "Red", "DecM23"], "sound": "grenade_bloodonade", "cell": 17, "smokeColors": "white", "fireColors": "default" }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_blood"] }, { "id": 16055, "name": "Nutcracker Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Nutcracker", "tags": ["Christmas2", "Red", "White", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 16056, "name": "New Year 2023 Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_NewYear2023", "tags": ["NewYears", "2023", "Red", "Blue", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 16057, "name": "Tambourine Grenade", "price": 5e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Tambourine", "tags": ["Rockstar", "JanM23", "Aug23", "Music"] }, "is_available": false, "unlock": "purchase" }, { "id": 16058, "name": "Blue Shell Grenade", "price": 2147483647, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Turtle", "tags": ["Community", "BWD"], "sound": "grenade_blueshell", "cell": 20, "smokeColors": "white", "fireColors": "white" }, "is_available": false, "unlock": "manual" }, { "id": 16059, "name": "Slop Bucket Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Pail", "tags": ["Premium", "farm", "FebM23", "Food"], "sound": "grenade_milkbucket", "cell": 16, "smokeColors": "white", "fireColors": "default" }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gre_pail"] }, { "id": 16060, "name": "Green Shell Grenade", "price": 3500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_TurtleGreen", "tags": ["Kart", "AprM23", "Turtle"] }, "is_available": false, "unlock": "purchase" }, { "id": 16061, "name": "Red Shell Grenade", "price": 1e4, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_TurtleRed", "tags": ["Kart", "AprM23", "Turtle", "JanM24"] }, "is_available": false, "unlock": "purchase" }, { "id": 16062, "name": "Equinox Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 16063, "name": "Kart Grenade", "price": 2500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Kart", "tags": ["Kart", "Aug23", "Green", "Eggs"] }, "is_available": false, "unlock": "purchase" }, { "id": 16064, "name": "Timebomb Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Timebomb", "tags": ["Kart", "Aug23", "Blue", "Yellow"], "sound": "grenade_Timebomb", "cell": 18, "smokeColors": "blue", "fireColors": "blue" }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_gre_timebomb"] }, { "id": 16065, "name": "Luchador Grenade", "price": 2500, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Luchador", "tags": ["WBs", "SepM23", "Wrestle", "Face"] }, "is_available": false, "unlock": "purchase" }, { "id": 16066, "name": "Smooth Brain Grenade", "price": 2100, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Brain", "tags": ["Oct23", "Halloween4", "Pink"] }, "is_available": false, "unlock": "purchase" }, { "id": 16067, "name": "Ancient Grenade", "price": 2e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 16068, "name": "Holideggs Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 16069, "name": "2024 Grenade", "price": 3e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_NewYear2024", "tags": ["DecM23", "2024", "NewYears", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 16070, "name": "Racer Frag Grenade", "price": 25e3, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_RaceCarFrag", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 16071, "name": "Rogue Tire Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_RaceCarPremium", "tags": ["JanM24", "Black", "Text", "Pireggi"], "sound": "grenade_tire", "cell": 21, "smokeColors": "white", "fireColors": "default" }, "is_available": true, "unlock": "premium", "activeProduct": false, "sku": ["item_gre_racecar"] }, { "id": 16074, "name": "Fusion Grenade", "price": 5, "item_type_id": 6, "item_type_name": "Grenade", "category_name": "Grenades", "exclusive_for_class": null, "item_data": { "meshName": "grenade_Fusion", "tags": ["FebM23", "White"], "sound": "grenade_fusion", "cell": 22, "smokeColors": "white", "fireColors": "default" }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gre_fusion"] }, { "id": 4500, "name": "The TriHard", "price": 0, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug", "tags": ["Default", "Red"] }, "is_available": true, "unlock": "default" }, { "id": 4501, "name": "GOLD TriHard", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Gold", "tags": ["Brown", "Gold", "Grey", "Gray", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 4502, "name": "Happy Bear TriHard", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Bear", "tags": ["White", "Pink", "Cute", "Heart"] }, "is_available": true, "unlock": "purchase" }, { "id": 4503, "name": "Rainbow TriHard", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Rainbow", "tags": ["White", "Red", "Orange", "Yellow", "Green", "Blue", "Purple", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 4504, "name": "Steampunk TriHard", "price": 1e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Steampunk", "tags": ["Brown", "Gears"] }, "is_available": true, "unlock": "purchase" }, { "id": 4505, "name": "Memphis TriHard", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Memphis", "tags": ["Memphis", "Black", "Green"] }, "is_available": true, "unlock": "purchase" }, { "id": 4506, "name": "Nuke Zone TriHard", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_NukeZone", "tags": ["Purple", "Blue", "Black", "Blurple", "Neon"] }, "is_available": true, "unlock": "purchase" }, { "id": 4507, "name": "Country Singer Tri-Hard", "price": 1e5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Snake", "tags": ["EggyCash", "Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 4508, "name": "Raid Land Tri-Hard", "price": 6500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_RaidLand", "tags": ["RaidLand", "Yellow", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 4509, "name": "Toxic Tri-Hard", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Toxic", "tags": ["Rotten", "Black", "Green", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 4510, "name": "Albino Snake Tri-Hard", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_SnakeAlbino", "tags": ["EggyCashAlbino", "White", "ABHS", "Snek", "Red", "Black", "Gray", "Grey"] }, "is_available": false, "unlock": "manual" }, { "id": 4511, "name": "Saint Patricks Skin Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_SaintPaddy", "tags": ["StPatricksDay", "MarM23", "Green", "Yellow", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 4512, "name": "Retro Tri-Hard", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Retro", "tags": ["Retro", "Premium", "Sep23", "Red", "Green", "Pixel", "Wings"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_aug_retro"] }, { "id": 4513, "name": "Easter Tri-Hard", "price": 1e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Easter", "tags": ["Easter", "JunM23", "Green", "Eggs", "MarM24"] }, "is_available": true, "unlock": "purchase" }, { "id": 4514, "name": "Car Tri-Hard", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_car", "tags": ["Cars", "Trains", "Truck", "Green", "Red", "Yellow"] }, "is_available": true, "unlock": "purchase" }, { "id": 4515, "name": "Merc Zone Tri-Hard", "price": 7e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Merc", "tags": ["Merc", "Suit", "Pink", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 4516, "name": "Summer Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Watergun", "tags": ["Summer", "JunM23", "Blue", "Orange", "Yellow", "Blue", "Orange", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4517, "name": "Buck Rogers Tri-Hard", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Buck", "tags": ["Promotional", "Black", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 4518, "name": "Galeggsy Tri-Hard", "price": 7500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Galaxy", "tags": ["Galeggsy", "AprM23", "Blue", "Purple", "Blurple", "Stars"] }, "is_available": false, "unlock": "purchase" }, { "id": 4519, "name": "Pencil Tri-Hard", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Pencil", "tags": ["Pencil", "Sep23", "Smile", "Yellow", "Blue", "Scissors"] }, "is_available": false, "unlock": "purchase" }, { "id": 4520, "name": "Halloween Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Halloween", "tags": ["Halloween", "Oct23", "Purple", "Green", "Bat", "Wings"] }, "is_available": false, "unlock": "purchase" }, { "id": 4521, "name": "Thanksgiving Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Turkey", "tags": ["NovM23", "Thanksgiving", "Brown", "Red", "Purple", "Eye"] }, "is_available": false, "unlock": "purchase" }, { "id": 4522, "name": "Christmas Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Present", "tags": ["Christmas", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 4523, "name": "New Year 2022 Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_NewYear2022", "tags": ["NewYears", "2022", "Blue", "Red", "Gold"] }, "is_available": false, "unlock": "purchase" }, { "id": 4524, "name": "ChantiGG Tri-Hard", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Chantigg", "tags": ["Drops", "Red", "Phone", "Booth"] }, "is_available": false, "unlock": "manual" }, { "id": 4525, "name": "Valentines Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Valentines", "tags": ["ValentinesDay", "Heart", "Brown", "Leopard", "Red"] }, "is_available": false, "unlock": "purchase" }, { "id": 4526, "name": "Kawaii Tri-Hard", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Cutesy", "tags": ["Kawaii", "Pink", "Yellow", "Blue"] }, "is_available": true, "unlock": "purchase" }, { "id": 4527, "name": "Cards Tri-Hard", "price": 1520, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Cards", "tags": ["EGGORG", "Apr23", "Blue", "Black", "Heart"] }, "is_available": false, "unlock": "purchase" }, { "id": 4528, "name": "Valkyrie Tri-Hard", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Valkyrie", "tags": ["Premium", "Valkyrie", "Gold", "Yellow", "Blue"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_gun_valk_aug"] }, { "id": 4529, "name": "Dino Tri-Hard", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Dino", "tags": ["Dino", "May23", "Orange"] }, "is_available": false, "unlock": "purchase" }, { "id": 4530, "name": "Eggpire Tri-Hard", "price": 12500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_spaceEggAlt", "tags": ["Eggwalker2", "Black", "Grey", "Gray", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 4531, "name": "SPORTS Tri-Hard", "price": 2500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Sports", "tags": ["Sports", "JulyM23", "Green", "Blue", "Tennis"] }, "is_available": false, "unlock": "purchase" }, { "id": 4532, "name": "Chicken Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Chicken", "tags": ["Chicken", "Red", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 4533, "name": "Breakfast Tri-Hard", "price": 1500, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Breakfast", "tags": ["Breakfast", "Food", "Spoon", "Red", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 4534, "name": "Bone Tri-Hard", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Bones", "tags": ["Halloween3", "OctM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 4535, "name": "New Year 2023 Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_NewYear2023", "tags": ["NewYears", "2023", "Red", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4536, "name": "Music Tri-Hard", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Music", "tags": ["Rockstar", "JanM23", "Gold", "Yellow", "Saxaphone", "Saxamaphone"] }, "is_available": false, "unlock": "purchase" }, { "id": 4537, "name": "Groundhog Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Groundhog", "tags": ["Groundhog", "Feb23", "Brown", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 4538, "name": "Farm Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Farm", "tags": ["Farm", "FebM23", "Food", "Red", "Yellow", "Orange", "Peppers"] }, "is_available": false, "unlock": "purchase" }, { "id": 4539, "name": "Equinox Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Equinox", "tags": ["Equinox", "July23", "Blue", "Yellow", "Sun", "Moon"] }, "is_available": false, "unlock": "purchase" }, { "id": 4540, "name": "Fusion Tri-Hard", "price": 5, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Fusion", "tags": ["Premium", "Fusion", "JulyM23", "White", "Blue", "Grey", "Gray"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_aug_fusion"] }, { "id": 4541, "name": "Kart Tri-Hard", "price": 5e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Kart", "tags": ["Kart", "Aug23", "Green", "Yellow"] }, "is_available": false, "unlock": "purchase" }, { "id": 4542, "name": "Ancient Tri-Hard", "price": 2e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Ruins", "tags": ["Nov23", "Mayan", "Gray", "Grey", "Green"] }, "is_available": false, "unlock": "purchase" }, { "id": 4543, "name": "Holideggs Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_PresentRed", "tags": ["Dec23", "Christmas3", "Gold", "Gray", "Grey", "Silver", "Black", "Yellow", "Bow", "Present"] }, "is_available": false, "unlock": "purchase" }, { "id": 4544, "name": "2024 Tri-Hard", "price": 3e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_NewYear2024", "tags": ["DecM23", "NewYears", "2024", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 4545, "name": "Racer Tri-Hard", "price": 25e3, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_RaceCar", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 4546, "name": "Cupid Tri-Hard", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Cupid", "tags": ["Feb24", "White", "Orange", "Grey", "Gray"] }, "is_available": false, "unlock": "premium" }, { "id": 4547, "name": "Green Snake Tri-Hard", "price": 15e4, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_SnakePatrick", "tags": ["Mar24", "White", "Green", "Grey", "Gray", "Albino"] }, "is_available": true, "unlock": "purchase" }, { "id": 4548, "name": "Flame Tri-Hard", "price": 2147483647, "item_type_id": 3, "item_type_name": "Primary", "category_name": "TriHard Primary Weapons", "exclusive_for_class": 6, "item_data": { "meshName": "gun_aug_Flames", "tags": ["Mar24", "Fire", "Brown", "Orange"] }, "is_available": false, "unlock": "manual" }, { "id": 15e3, "name": "The Whisk Melee", "price": 0, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "whisk", "tags": ["Silver"] }, "is_available": true, "unlock": "default" }, { "id": 15001, "name": "Corn Melee", "price": 0, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_corn", "tags": ["Yellow", "Green", "Food", "Meme"] }, "is_available": true, "unlock": "default" }, { "id": 15002, "name": "Club Melee", "price": 0, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_stick", "tags": ["Brown"] }, "is_available": true, "unlock": "default" }, { "id": 15003, "name": "Gold Melee", "price": 2500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_gold", "tags": ["Brown", "Gold", "Whisk"] }, "is_available": true, "unlock": "purchase" }, { "id": 15004, "name": "Pink Bear Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_bear", "tags": ["Pink", "Cute", "Heart", "Whisk"] }, "is_available": true, "unlock": "purchase" }, { "id": 15005, "name": "Steampunk Melee", "price": 7500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_steampunk", "tags": ["Brown", "Gold", "Whisk"] }, "is_available": true, "unlock": "purchase" }, { "id": 15006, "name": "Rainbow Melee", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_rainbow", "tags": ["Red", "Orange", "Yellow", "Green", "Blue", "Clouds", "Whisk"] }, "is_available": true, "unlock": "purchase" }, { "id": 15007, "name": "Memphis Melee", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_memphis", "tags": ["Black", "White", "Rainbow", "Whisk"] }, "is_available": true, "unlock": "purchase" }, { "id": 15008, "name": "Rotten Melee", "price": 15e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_toxic", "tags": ["Pipe", "Green", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 15009, "name": "Car Melee", "price": 2e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_shift", "tags": ["Black", "Silver", "Gear"] }, "is_available": true, "unlock": "purchase" }, { "id": 15010, "name": "Brown Snake Melee", "price": 1e5, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_snake", "tags": ["Brown", "Snek"] }, "is_available": true, "unlock": "purchase" }, { "id": 15011, "name": "Hoe Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_hoe", "tags": ["FebM23", "farm", "Tools"] }, "is_available": false, "unlock": "purchase" }, { "id": 15012, "name": "Flame Melee", "price": 2147483647, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_flame", "tags": ["Orange", "Yellow", "Fire"] }, "is_available": false, "unlock": "manual" }, { "id": 15013, "name": "Valkyrie Melee", "price": 6, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_valkyrie", "tags": ["Gold", "Blue", "Yellow", "Premium"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_melee_valk"] }, { "id": 15014, "name": "BWD Wizard Melee", "price": 2147483647, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_wizard", "tags": ["Drops4", "Mar23", "Blue", "Brown", "Staff"] }, "is_available": false, "unlock": "manual" }, { "id": 15015, "name": "Sneaker Melee", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_sneaker", "tags": ["Bros", "MarM23", "White", "Blue", "Shoe"] }, "is_available": false, "unlock": "purchase" }, { "id": 15016, "name": "Fiddle Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_fiddle", "tags": ["StPatricksDay", "MarM23", "Music", "Brown", "Mar24"] }, "is_available": true, "unlock": "purchase" }, { "id": 15017, "name": "Medieval Key Melee", "price": 2147483647, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_key", "tags": ["Apr23", "Newsletter", "Gold", "Yellow"] }, "is_available": false, "unlock": "manual" }, { "id": 15018, "name": "Galeggsy Whisk", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_galaxy", "tags": ["AprM23", "Galeggsy", "Blue", "Purple", "Planets", "OctM23"] }, "is_available": false, "unlock": "purchase" }, { "id": 15019, "name": "Giant Spoon Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_spoon", "tags": ["AprM23", "Silver", "Food"] }, "is_available": true, "unlock": "purchase" }, { "id": 15020, "name": "Albino Snake Melee", "price": 2147483647, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_albino", "tags": ["Giveaway", "White", "ABHS", "Snek"] }, "is_available": false, "unlock": "manual" }, { "id": 15021, "name": "Forkin' Fork! Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_fork", "tags": ["Silver", "Food"] }, "is_available": true, "unlock": "purchase" }, { "id": 15022, "name": "Bone Bonker", "price": 4500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_bone", "tags": ["May23", "Dino2", "Caveman"] }, "is_available": false, "unlock": "purchase" }, { "id": 15023, "name": "Stone Hammer Melee", "price": 5, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_rock", "tags": ["May23", "Nov23", "Dino2", "Grey", "Gray"] }, "is_available": false, "unlock": "premium", "activeProduct": true, "sku": ["item_melee_stone"] }, { "id": 15024, "name": "Eggflation Whisk", "price": 8e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_eggflation", "tags": ["MayM23", "Eggflation", "Gold", "Yellow", "80k"] }, "is_available": true, "unlock": "purchase" }, { "id": 15025, "name": "Butterknife Melee", "price": 6500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_butterknife", "tags": ["MayM23", "Eggflation", "Silver", "Food"] }, "is_available": true, "unlock": "purchase" }, { "id": 15026, "name": "Shellfie Stick Melee", "price": 7500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_selfiestick", "tags": ["Jun23", "Photo", "Cheese"] }, "is_available": false, "unlock": "purchase" }, { "id": 15027, "name": "Spatula Melee", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_spatula", "tags": ["Jun23", "Silver"] }, "is_available": true, "unlock": "purchase" }, { "id": 15028, "name": "Popsicle Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_popsicle", "tags": ["JunM23", "Summer2", "Pink", "Food"] }, "is_available": false, "unlock": "purchase" }, { "id": 15029, "name": "Wrench Melee", "price": 4500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_wrench", "tags": ["JunM23", "Summer2", "Blue", "Yellow", "Tools"] }, "is_available": true, "unlock": "purchase" }, { "id": 15030, "name": "Fusion Melee", "price": 5, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_fusion", "tags": ["JunM23", "Blue", "White", "Gray", "Grey"] }, "is_available": true, "unlock": "premium", "activeProduct": true, "sku": ["item_melee_fusion"] }, { "id": 15031, "name": "Equinox Melee", "price": 3e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_equinox", "tags": ["July23", "Equinox", "Blue", "Yellow", "Sun", "Moon", "Whisk"] }, "is_available": false, "unlock": "purchase" }, { "id": 15032, "name": "Crowbar Melee", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_crowbar", "tags": ["July23", "Blue", "Yellow", "Red", "Tools"] }, "is_available": true, "unlock": "purchase" }, { "id": 15033, "name": "Hockey Melee", "price": 8e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_hockey", "tags": ["JulyM23", "Sports2", "Stick"] }, "is_available": false, "unlock": "purchase" }, { "id": 15034, "name": "Shovel Melee", "price": 7500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_shovel", "tags": ["JulyM23", "Pink", "Yellow", "Blue"] }, "is_available": false, "unlock": "purchase" }, { "id": 15035, "name": "MenoXD Katana", "price": 125e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_meno", "tags": ["JulyM23", "Red", "Black"] }, "is_available": true, "unlock": "purchase" }, { "id": 15036, "name": "Kart Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_kart", "tags": ["Aug23", "Kart", "Red", "Blue", "Whisk"] }, "is_available": false, "unlock": "purchase" }, { "id": 15037, "name": "Harrison Cat Melee", "price": 5, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_harrison", "tags": ["AugM23", "Drops5", "Black", "White", "Cat"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_melee_cat"] }, { "id": 15039, "name": "Ruler Melee", "price": 6500, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_ruler", "tags": ["Sep23", "Pencil3", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 15040, "name": "Fighting Fish Slapper", "price": 2147483647, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_fish", "tags": ["Sep23", "Bundle", "Food"] }, "is_available": false, "unlock": "premium" }, { "id": 15041, "name": "Folding Chair Melee", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_chair", "tags": ["SepM23", "WBs", "Wrestle", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 15042, "name": "Pitchfork Melee", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_devil", "tags": ["Oct23", "Halloween4", "Red", "Black"] }, "is_available": false, "unlock": "purchase" }, { "id": 15043, "name": "Rolling Pin Whalloper", "price": 8e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_rollingpin", "tags": ["Oct23", "Brown"] }, "is_available": true, "unlock": "purchase" }, { "id": 15044, "name": "Ancient Club", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_ruins", "tags": ["Nov23", "Green", "Gray", "Grey"] }, "is_available": false, "unlock": "purchase" }, { "id": 15045, "name": "Mayan Macuahuitl", "price": 5, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_mayan", "tags": ["Nov23", "Red", "Black", "Brown"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_melee_mayan"] }, { "id": 15046, "name": "Turkey Drumstick", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_drumstick", "tags": ["NovM23", "Red", "Black", "Brown"] }, "is_available": false, "unlock": "purchase" }, { "id": 15047, "name": "The Turkey Carver", "price": 5, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_carver", "tags": ["NovM23", "Blue", "Black", "Gas"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_melee_turkcar"] }, { "id": 15048, "name": "The Candy Cane-r", "price": 1e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_candycane", "tags": ["Dec23", "Blue", "Black", "Gas"] }, "is_available": false, "unlock": "purchase" }, { "id": 15049, "name": "Elf on a Shelf Melee", "price": 2147483647, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_elf", "tags": ["Dec23", "Blue", "Black", "Gas"] }, "is_available": false, "unlock": "premium" }, { "id": 15050, "name": "2024 Whisk", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_newyear2024", "tags": ["DecM23", "2024", "NewYears", "Blue", "White"] }, "is_available": false, "unlock": "purchase" }, { "id": 15051, "name": "Racer Lug Wrench", "price": 5e4, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_lugwrench", "tags": ["JanM24", "Racer", "White", "Orange", "Grey", "Gray"] }, "is_available": true, "unlock": "purchase" }, { "id": 15052, "name": "Groundhog Melee", "price": 7e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_groundhog", "tags": ["Feb24", "Groundhog", "White", "Orange", "Grey", "Gray", "Feb24"] }, "is_available": false, "unlock": "purchase" }, { "id": 15053, "name": "Buck Rogers Melee", "price": 2147483647, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_buck", "tags": ["Jan24", "White", "Orange", "Grey", "Gray"] }, "is_available": false, "unlock": "manual" }, { "id": 15054, "name": "Vuvuzela Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_vuvuzela", "tags": ["FebM24", "White", "Orange", "Grey", "Gray"] }, "is_available": false, "unlock": "purchase" }, { "id": 15055, "name": "World Cup Melee", "price": 5, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_cup", "tags": ["FebM24", "Gold", "Yellow"] }, "is_available": false, "unlock": "premium", "activeProduct": false, "sku": ["item_melee_worldcup"] }, { "id": 15056, "name": "Chocolate Bunny Melee", "price": 5e3, "item_type_id": 7, "item_type_name": "Melee", "category_name": "Melee", "exclusive_for_class": null, "item_data": { "meshName": "melee_chocolatebun", "tags": ["MarM24", "Rabbit", "Brown", "Easter", "Gold"] }, "is_available": true, "unlock": "purchase" }];
var ChwRewardIds = [1012, 1023, 1115, 1256, 1257, 1258, 2017, 2394, 1118, 2007, 2396, 1284, 2395, 2085, 2132, 2201, 2184, 1260, 2153, 1282, 2104, 1121, 1017, 3034, 3402, 3802, 1175, 2100, 2354, 1179, 2065, 3113, 4003, 2266, 2315, 1237, 1206, 4201, 2135, 2086, 2126, 2134, 2168, 2247, 2209, 1203, 3833, 4017, 2155, 15015, 2117, 1263, 1205, 1150, 1225, 3117, 1172, 4213, 3639, 1198, 1127, 1220, 1224, 1323, 4216, 1137, 15024, 3820, 16013, 1183, 3017, 15010, 3645, 1101, 3437, 1078, 1167, 1076, 1210, 1211, 1213, 3625, 1080, 1079, 1075, 1074, 1073, 1066, 4524, 3012, 3020, 4212, 4008, 4220, 3821, 3620, 3420, 4006, 3108, 3612, 3020, 16010, 4020, 4206, 4208, 15012];
function cloneMesh(name, scene, parent, material) {
let mesh2 = globalScene.cloneMesh(name, scene, parent);
scene.addMesh(mesh2);
if (material) {
mesh2.material = material;
} else if (mesh2.material && mesh2.material._scene != scene) {
mesh2.material = getMaterialByName(mesh2.material.name, scene);
}
return mesh2;
}
function cloneSkeleton(name, scene) {
let skeleton = globalScene.cloneSkeleton(name, scene);
scene.addSkeleton(skeleton);
return skeleton;
}
function getMaterialByName(name, scene) {
let mat = scene.getMaterialByName(name);
if (!mat) {
mat = globalScene.getMaterialByName(name).clone(name, scene);
scene.addMaterial(mat);
}
return mat;
}
BABYLON.Skeleton.prototype.disableBlending = function() {
this.bones.forEach(function(bone) {
bone.animations.forEach(function(animation) {
animation.enableBlending = false;
});
});
};
BABYLON.Scene.prototype.cloneMesh = function(name, scene, parent) {
var mesh2 = this.getMeshByName(name);
let clonedMesh = new BABYLON.Mesh(name, scene, parent, mesh2);
return clonedMesh;
};
BABYLON.chrome84BugWorkaround = false;
BABYLON.Scene.prototype.cloneSkeleton = function(name, scene) {
var skeleton = this.getSkeletonByName(name).clone();
skeleton.name = name + Date.now();
skeleton._scene = scene;
return skeleton;
};
BABYLON.DynamicTexture.prototype.clearRect = function(x, y, w, h) {
this._context.clearRect(x, y, w, h);
};
BABYLON.AbstractMesh.prototype.setLayerMask = function(mask) {
this.layerMask = mask;
var children = this.getChildMeshes();
for (var i2 = 0; i2 < children.length; i2++) {
children[i2].setLayerMask(mask);
}
};
BABYLON.AbstractMesh.prototype.setRenderingGroupId = function(id) {
this.renderingGroupId = id;
var children = this.getChildMeshes();
for (var i2 = 0; i2 < children.length; i2++) {
children[i2].setRenderingGroupId(id);
}
};
BABYLON.TransformNode.prototype.setVisible = function(visible) {
this.isVisible = visible;
this._isWorldMatrixFrozen = !visible;
var children = this.getChildTransformNodes();
for (var i2 = 0; i2 < children.length; i2++) {
children[i2].setVisible(visible);
}
};
BABYLON.AbstractMesh.prototype.setMaterial = function(mat) {
this.material = mat;
var children = this.getChildMeshes();
for (var i2 = 0; i2 < children.length; i2++) {
children[i2].setMaterial(mat);
}
};
BABYLON.Vector3.ClampToRef = function(value, min, max, ref) {
var x = value.x;
x = x > max.x ? max.x : x;
x = x < min.x ? min.x : x;
var y = value.y;
y = y > max.y ? max.y : y;
y = y < min.y ? min.y : y;
var z = value.z;
z = z > max.z ? max.z : z;
z = z < min.z ? min.z : z;
ref.copyFromFloats(x, y, z);
};
function Bullet(scene) {
this.scene = scene;
this.x = 0;
this.y = 0;
this.z = 0;
this.dx = 0;
this.dy = 0;
this.dz = 0;
this.active = false;
this.player_ = null;
this.damage = 20;
this.range = 0;
this.velocity = 0;
this.hitsMap = false;
this.origin = new BABYLON.Vector3();
this.direction = new BABYLON.Vector3();
this.end = new BABYLON.Vector3();
this.meshName = "";
this.weaponClassId = 0;
this.actor = new BulletActor(this);
}
Bullet.damageExp = 4;
Bullet.v1 = new BABYLON.Vector3();
Bullet.v2 = new BABYLON.Vector3();
Bullet.v3 = new BABYLON.Vector3();
Bullet.position = new BABYLON.Vector3();
Bullet.fire = function(player, pos, dir, weaponClass) {
var bullet = munitionsManager.bulletPool.retrieve();
bullet.fireThis(player, pos, dir, weaponClass);
};
Bullet.prototype.fireThis = function(player, pos, dir, weaponClass) {
this.player_ = player;
this.x = pos.x;
this.y = pos.y;
this.z = pos.z;
this.origin.set(this.x, this.y, this.z);
this.direction.copyFrom(dir).normalize().scaleInPlace(weaponClass.velocity);
this.dx = this.direction.x;
this.dy = this.direction.y;
this.dz = this.direction.z;
this.weaponClass = weaponClass;
this.damage = weaponClass.damage;
this.active = true;
this.range = weaponClass.range;
this.velocity = weaponClass.velocity;
this.hitsMap = false;
this.powerful = false;
this.dmgTypeId = weaponClass.dmgTypeId;
var res = Collider.rayCollidesWithMap(pos, dir, Collider.projectileCollidesWithCell);
if (res) {
this.end.copyFrom(res.pick.pickedPoint);
this.range = BABYLON.Vector3.Distance(pos, res.pick.pickedPoint);
this.hitsMap = true;
}
if (player.activeShellStreaks & ShellStreak.EggBreaker) {
this.powerful = true;
this.damage *= 1.5;
}
if (this.player_.weapon.tracer == 0) {
this.actor.fire(this.powerful);
} else {
this.actor.delayFrames = Number.MAX_SAFE_INTEGER;
}
};
Bullet.prototype.remove = function() {
munitionsManager.bulletPool.recycle(this);
this.actor.remove();
};
Bullet.prototype.update = function() {
Bullet.position.set(this.x, this.y, this.z);
if (this.range < this.velocity) {
this.direction.scaleInPlace(this.range / this.velocity);
}
if (Collider.rayCollidesWithPlayer(Bullet.position, this.direction, this)) {
return;
}
;
this.x += this.dx;
this.y += this.dy;
this.z += this.dz;
this.range -= this.velocity;
if (this.range <= 0) {
if (this.hitsMap) {
var pos = this.end;
var dx = -this.dx * 0.1;
var dy = -this.dy * 0.1;
var dz = -this.dz * 0.1;
addBulletHitSprite(pos.x, pos.y, pos.z, dx, dy, dz);
}
this.remove();
return;
}
};
Bullet.prototype.collidesWithPlayer = function(player, normal) {
Bullet.v1.x = this.dx;
Bullet.v1.y = this.dy;
Bullet.v1.z = this.dz;
Bullet.v1.normalize();
var dot = -BABYLON.Vector3.Dot(Bullet.v1, normal) * 0.8 + 0.2;
let damageMod = 1;
var damage = this.damage * Math.pow(dot, Bullet.damageExp + Math.pow(dot, Bullet.damageExp) * damageMod);
if (isNaN(damage)) {
console.error("Bullet.collidesWithPlayer damage is NaN", dot, Bullet.damageExp, damageMod, Bullet.v1, normal);
}
hitPlayer(player, this, damage, Bullet.v1.x, Bullet.v1.z);
this.remove();
};
var BVH3 = class {
constructor() {
var v1 = new BABYLON.Vector3(0, 0, 0);
var v2 = new BABYLON.Vector3(minMap.width, minMap.height, minMap.depth);
this.world = new BABYLON.BoundingBox(v1, v2);
this.bvh = this.createNode(this.world, 2);
this.checkTick = 0;
}
add(object, bvh) {
bvh = bvh || this.bvh;
for (var i2 = 0; i2 < bvh.length; i2++) {
var vb = bvh[i2];
if (BABYLON.BoundingBox.Intersects(object.bb, vb)) {
if (vb.maximumWorld.x - vb.minimumWorld.x > (object.bb.maximumWorld.x - object.bb.minimumWorld.x) * 0.5 && vb.maximumWorld.y - vb.minimumWorld.y > (object.bb.maximumWorld.y - object.bb.minimumWorld.y) * 0.5 && vb.maximumWorld.z - vb.minimumWorld.z > (object.bb.maximumWorld.z - object.bb.minimumWorld.z) * 0.5) {
if (vb.bvh.length == 0) {
vb.bvh = this.createNode(vb, 2);
}
object.checkTick = 0;
this.add(object, vb.bvh);
} else {
vb.objects.push(object);
}
}
}
}
createNode(bb, divisions) {
var boxes = [];
var w = (bb.maximumWorld.x - bb.minimumWorld.x) / divisions;
var d = (bb.maximumWorld.z - bb.minimumWorld.z) / divisions;
if (w > minMap.height) {
var yMin = 0;
var yMax = minMap.height;
var h = minMap.height;
} else {
var yMin = bb.minimumWorld.y;
var yMax = bb.maximumWorld.y;
var h = (yMax - yMin) / divisions;
}
for (var x = bb.minimumWorld.x; x < bb.maximumWorld.x; x += w) {
for (var y = yMin; y < yMax; y += h) {
for (var z = bb.minimumWorld.z; z < bb.maximumWorld.z; z += d) {
var min = new BABYLON.Vector3(x, y, z);
var max = new BABYLON.Vector3(x + w, y + h, z + d);
var box = new BABYLON.BoundingBox(min, max);
box.bvh = [];
box.objects = [];
boxes.push(box);
}
}
}
return boxes;
}
// Finds all objects with bounding boxes that intersect the provided bounding box
getObjects(bb, callback) {
this.checkTick++;
this.recurseObjects(bb, this.bvh, callback);
}
recurseObjects(bb, bvh, callback) {
for (var i2 = 0; i2 < bvh.length; i2++) {
var vb = bvh[i2];
if (BABYLON.BoundingBox.Intersects(bb, vb)) {
for (var c = 0; c < vb.objects.length; c++) {
var object = vb.objects[c];
if (object.checkTick != this.checkTick && BABYLON.BoundingBox.Intersects(bb, object.bb)) {
object.checkTick = this.checkTick;
callback(vb.objects[c]);
}
}
this.recurseObjects(bb, vb.bvh, callback);
}
}
}
getObjectsWithRay(origin, direction, callback) {
this.checkTick++;
this.recurseObjectsWithRay(origin, direction, this.bvh, callback);
}
recurseObjectsWithRay(origin, direction, bvh, callback) {
for (var i2 = 0; i2 < bvh.length; i2++) {
var vb = bvh[i2];
if (BABYLON.BoundingBox.IntersectsRay(vb, origin, direction)) {
for (var c = 0; c < vb.objects.length; c++) {
var object = vb.objects[c];
if (object.checkTick != this.checkTick && BABYLON.BoundingBox.IntersectsRay(object.bb, origin, direction)) {
object.checkTick = this.checkTick;
callback(vb.objects[c]);
}
}
this.recurseObjectsWithRay(origin, direction, vb.bvh, callback);
}
}
}
};
if (!G.catalog) {
G.catalog = new Catalog();
}
function Catalog() {
if (Items === void 0 || Items === null) {
throw "Items is undefined or null, cannot create Catalog";
}
this.isSetup = false;
this.filterItems = function(itemList, filterFunc) {
var filteredItems = [];
for (var i2 = 0; i2 < itemList.length; i2++) {
if (filterFunc(itemList[i2])) {
filteredItems.push(itemList[i2]);
}
}
return filteredItems;
};
this.findItemInListById = function(itemId, itemList) {
for (var i2 = 0; i2 < itemList.length; i2++) {
if (itemList[i2] && itemList[i2].id === itemId) {
return itemList[i2];
}
}
return null;
};
this.findItemsByIds = function(itemIds) {
return Items.filter((i2) => {
return itemIds.includes(i2.id);
});
};
this.findItemById = function(itemId) {
return this.findItemInListById(itemId, Items);
};
this.findItemBy8BitItemId = function(itemType, classIdx, itemId8Bit) {
if (this.isSetup === false) {
this.setupCatalog();
}
if (classIdx === void 0 || classIdx >= CharClass.length)
return null;
var realItemId = itemId8Bit;
switch (itemType) {
case ItemType2.Hat:
if (itemId8Bit === 0) {
return null;
}
return this.findItemInListById(realItemId, this.hats);
case ItemType2.Stamp:
if (itemId8Bit === 0) {
return null;
}
return this.findItemInListById(realItemId, this.stamps);
case ItemType2.Primary:
return this.findItemInListById(realItemId, this.forClass[classIdx].forWeaponSlot[Slot.Primary]);
case ItemType2.Secondary:
return this.findItemInListById(realItemId, this.forClass[classIdx].forWeaponSlot[Slot.Secondary]);
case ItemType2.Grenade:
return this.findItemInListById(realItemId, this.grenades);
case ItemType2.Melee:
return this.findItemInListById(realItemId, this.melee);
}
};
this.addWeaponFunctions = function(weaponItem) {
weaponItem.instantiateNew = function(avatar) {
var instance;
if (this.exclusive_for_class === null) {
instance = new Cluck9mm(avatar, this.item_data.meshName);
} else {
instance = new G.classes[this.exclusive_for_class].weapon(avatar, this.item_data.meshName);
}
if (avatar.actor) {
avatar.actor.setWeaponSkeleton(instance.actor.skeleton);
}
return instance;
};
};
this.addGrenadeFunctions = function(grenadeItem) {
grenadeItem.instantiateNew = function(avatar) {
let mesh2 = cloneMesh(this.item_data.meshName, avatar.scene);
let instance = {
scene: avatar.scene,
player: avatar,
actor: {
mesh_: mesh2,
dispose: () => {
mesh2.dispose();
}
}
};
mesh2.position.y = 0.5;
mesh2.position.z = 1;
return instance;
};
};
this.addMeleeFunctions = function(meleeItem) {
meleeItem.instantiateNew = function(avatar) {
let mesh2 = cloneMesh(this.item_data.meshName, avatar.scene);
let instance = {
scene: avatar.scene,
player: avatar,
actor: {
weaponMesh: mesh2,
skeleton: cloneSkeleton("melee_skeleton", avatar.scene),
dispose: () => {
mesh2.dispose();
}
}
};
if (avatar.actor) {
avatar.actor.setWeaponSkeleton(instance.actor.skeleton);
}
return instance;
};
};
this.getTaggedItems = function(tag, itemType) {
if (!tag)
return [];
tag = tag.replace(/\s/g, "");
const tags = tag.split(",");
const filterTagFunc = function(item) {
const hasTags = item.item_data.tags !== void 0 && item.item_data.tags !== null && item.item_data.tags.length > 0;
if (hasTags) {
if (itemType !== void 0 && item.item_type_name !== getKeyByValue(ItemType2, itemType)) {
return false;
}
let hasTag = false;
item.item_data.tags.forEach((iTag) => {
tags.forEach((tag2) => {
if (tag2 === iTag) {
hasTag = true;
}
});
});
return hasTag;
}
return false;
};
return this.filterItems(Items, filterTagFunc);
};
this.getTaggedItemsWithItemType = (tag, itemType) => {
};
this.premiumSoundValid = function(i2) {
return i2.hasOwnProperty("unlock") && i2.unlock === "premium" || i2.unlock === "manual" && i2.item_data.meshName === "gun_cluck9mm_CubicCastles";
};
this.getPremiumGunMeshNames = function() {
Object.keys(CharClass).forEach((key) => {
if (key !== "Soldier") {
PremMeshNames[key] = Items.filter((i2) => hasValue(i2.exclusive_for_class) && i2.exclusive_for_class === CharClass[key] && this.premiumSoundValid(i2)).map((i2) => i2.item_data.meshName);
}
;
});
Object.keys(ItemType2).forEach((key) => {
if (key !== "Primary") {
PremMeshNames[key] = Items.filter((i2) => hasValue(i2.item_type_id) && i2.item_type_id === ItemType2[key] && this.premiumSoundValid(i2)).map((i2) => i2.item_data.meshName);
} else if (key === "Primary") {
PremMeshNames["Soldier"] = Items.filter((i2) => hasValue(i2.item_type_id) && i2.item_type_id === ItemType2.Primary && !hasValue(i2.exclusive_for_class) && this.premiumSoundValid(i2)).map((i2) => i2.item_data.meshName);
}
});
};
this.setupCatalog = function() {
this.hats = [];
this.stamps = [];
this.primaryWeapons = [];
this.secondaryWeapons = [];
this.grenades = [];
this.melee = [];
this.forClass = [];
for (var i2 = 0; i2 < Items.length; i2++) {
switch (Items[i2].item_type_id) {
case ItemType2.Hat:
this.hats.push(Items[i2]);
break;
case ItemType2.Stamp:
this.stamps.push(Items[i2]);
break;
case ItemType2.Primary:
this.primaryWeapons.push(Items[i2]);
this.addWeaponFunctions(Items[i2]);
break;
case ItemType2.Secondary:
this.secondaryWeapons.push(Items[i2]);
this.addWeaponFunctions(Items[i2]);
break;
case ItemType2.Grenade:
this.grenades.push(Items[i2]);
this.addGrenadeFunctions(Items[i2]);
break;
case ItemType2.Melee:
this.melee.push(Items[i2]);
this.addMeleeFunctions(Items[i2]);
break;
}
}
for (var cIdx = 0; cIdx < CharClass.length; cIdx++) {
var isFreeSharedFunc = function(item) {
return item.price === 0 && item.exclusive_for_class === null;
};
var isFreeClassExclusiveFunc = function(item) {
return item.price === 0 && item.exclusive_for_class === cIdx;
};
var isPaidSharedFunc = function(item) {
return item.price > 0 && item.exclusive_for_class === null;
};
var isPaidClassExclusiveFunc = function(item) {
return item.price > 0 && item.exclusive_for_class === cIdx;
};
var outer = this;
var createClassWeaponListFunc = function(itemList) {
var itemList = outer.filterItems(itemList, isFreeSharedFunc).concat(outer.filterItems(itemList, isFreeClassExclusiveFunc)).concat(outer.filterItems(itemList, isPaidSharedFunc)).concat(outer.filterItems(itemList, isPaidClassExclusiveFunc));
return itemList;
};
var classItems = {
primaryWeapons: createClassWeaponListFunc(this.primaryWeapons),
secondaryWeapons: createClassWeaponListFunc(this.secondaryWeapons)
};
classItems.forWeaponSlot = [classItems.primaryWeapons, classItems.secondaryWeapons];
this.forClass.push(classItems);
}
this.isSetup = true;
};
if (!this.isSetup) {
this.setupCatalog();
}
}
var Collider = {
init: function(scene) {
Collider.playerCollisionMesh = BABYLON.MeshBuilder.CreateBox("pc", { size: 0.5, height: 0.6 }, scene);
Collider.playerCollisionMesh.position.y = 0.3;
Collider.playerCollisionMesh.bakeCurrentTransformIntoVertices();
Collider.playerCollisionMesh.setEnabled(false);
Collider.wedgeCollisionMesh = BABYLON.MeshBuilder.CreateBox("", { size: 1.5 }, scene);
Collider.wedgeCollisionMesh.position.y = -0.75;
Collider.wedgeCollisionMesh.bakeCurrentTransformIntoVertices();
Collider.wedgeCollisionMesh.rotation.x = -Math.PI / 4;
Collider.wedgeCollisionMesh.bakeTransformIntoVertices(Collider.wedgeCollisionMesh.getWorldMatrix());
Collider.wedgeCollisionMesh.setEnabled(false);
Collider.iwedgeCollisionMesh = BABYLON.MeshBuilder.CreateBox("", { size: 1.5 }, scene);
Collider.iwedgeCollisionMesh.position.y = 0.75;
Collider.iwedgeCollisionMesh.bakeCurrentTransformIntoVertices();
Collider.iwedgeCollisionMesh.rotation.x = -Math.PI / 4;
Collider.iwedgeCollisionMesh.bakeTransformIntoVertices(Collider.iwedgeCollisionMesh.getWorldMatrix());
Collider.iwedgeCollisionMesh.setEnabled(false);
Collider.fullCollisionMesh = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, scene);
Collider.fullCollisionMesh.setEnabled(false);
},
v1: new BABYLON.Vector3(),
v2: new BABYLON.Vector3(),
v3: new BABYLON.Vector3(),
v4: new BABYLON.Vector3(),
v5: new BABYLON.Vector3(),
ray: new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 1),
matrix: new BABYLON.Matrix(),
meshCollidesWithMap: function(mesh2, pos) {
var cellsChecked = {};
if (isNaN(pos.x) || isNaN(pos.y) || isNaN(pos.z))
return true;
var bbox = mesh2.getBoundingInfo().boundingBox;
for (var i2 = 0; i2 < bbox.vectors.length; i2++) {
var cx = Math.floor(pos.x + bbox.vectors[i2].x);
var cy = Math.floor(pos.y + bbox.vectors[i2].y);
var cz = Math.floor(pos.z + bbox.vectors[i2].z);
if (cx < 0 || cx >= map.width || cz < 0 || cz >= map.depth || cy < 0)
return true;
var checkId = cx + cy * 1e3 + cz * 1e6;
if (cy < map.height) {
if (!cellsChecked[checkId]) {
var res = Collider.meshCollidesWithCell(mesh2, pos, cx, cy, cz);
if (res)
return res;
cellsChecked[checkId] = true;
}
}
}
return false;
},
meshCollidesWithCell: function(mesh2, pos, cx, cy, cz, ignoreSoft) {
var cell = map.data[cx][cy][cz];
if (cell.idx) {
var mapMesh2 = mapMeshes[cell.idx];
if (ignoreSoft && mapMesh2.softness) {
return false;
}
switch (mapMesh2.colliderType) {
case "full":
return { x: cx, y: cy, z: cz, cell, mesh: Collider.fullCollisionMesh };
case "ladder":
if (mesh2.name != "pc")
return false;
break;
case "none":
return false;
}
mesh2.position.x = pos.x - cx - 0.5;
mesh2.position.y = pos.y - cy - 0.5;
mesh2.position.z = pos.z - cz - 0.5;
Collider.v1.set(-mesh2.position.x, -mesh2.position.y, -mesh2.position.z);
mesh2.setPivotPoint(Collider.v1);
mesh2.rotation.x = -cell.rx;
mesh2.rotation.y = -cell.ry;
mesh2.rotation.z = -cell.rz;
mesh2.computeWorldMatrix();
var m = cell.colliderMesh.intersectsMesh(mesh2, cell.colliderPrecise, cell.colliderChildren);
if (m) {
return { x: cx, y: cy, z: cz, cell, mesh: m };
}
}
return false;
},
rayCollidesWithMap: function(origin, direction, callback) {
if (isNaN(origin.x) || isNaN(origin.y) || isNaN(origin.z))
return false;
if (origin.x < 0 || origin.x >= map.width || origin.z < 0 || origin.z >= map.depth || origin.y < 0 || origin.y >= map.height) {
return false;
}
var radius = direction.length();
var x = Math.floor(origin.x);
var y = Math.floor(origin.y);
var z = Math.floor(origin.z);
var dx = direction.x;
var dy = direction.y;
var dz = direction.z;
var stepX = Math.sign(dx);
var stepY = Math.sign(dy);
var stepZ = Math.sign(dz);
var tMaxX = Collider.intbound(origin.x, dx);
var tMaxY = Collider.intbound(origin.y, dy);
var tMaxZ = Collider.intbound(origin.z, dz);
var tDeltaX = stepX / dx;
var tDeltaY = stepY / dy;
var tDeltaZ = stepZ / dz;
if (dx === 0 && dy === 0 && dz === 0)
return false;
radius /= Math.sqrt(dx * dx + dy * dy + dz * dz);
while (
/* ray has not gone past bounds of world */
(stepX > 0 ? x < map.width : x >= 0) && (stepY > 0 ? y < map.height : y >= 0) && (stepZ > 0 ? z < map.depth : z >= 0)
) {
if (!(x < 0 || y < 0 || z < 0 || x >= map.width || y >= map.height || z >= map.depth)) {
var res = callback(origin, direction, { x, y, z });
if (res && mapMeshes[res.cell.idx].softness != "verysoft") {
return res;
}
}
if (tMaxX < tMaxY) {
if (tMaxX < tMaxZ) {
if (tMaxX > radius)
break;
x += stepX;
tMaxX += tDeltaX;
} else {
if (tMaxZ > radius)
break;
z += stepZ;
tMaxZ += tDeltaZ;
}
} else {
if (tMaxY < tMaxZ) {
if (tMaxY > radius)
break;
y += stepY;
tMaxY += tDeltaY;
} else {
if (tMaxZ > radius)
break;
z += stepZ;
tMaxZ += tDeltaZ;
}
}
}
},
intbound: function(s, ds) {
if (ds < 0) {
return Collider.intbound(-s, -ds);
} else {
s = (s % 1 + 1) % 1;
return (1 - s) / ds;
}
},
getCellForRay: function(voxel) {
try {
var cell = map.data[voxel.x][voxel.y][voxel.z];
} catch (e2) {
console.log(voxel);
}
if (!cell || !cell.mesh)
return false;
switch (cell.mesh.colliderType) {
case "none":
case "ladder":
return false;
}
return cell;
},
projectileCollidesWithCell: function(origin, direction, voxel) {
var cell = Collider.getCellForRay(voxel);
if (!cell)
return false;
if (cell.mesh.softness)
return false;
colliderMesh = cell.colliderMesh;
Collider.matrix.copyFrom(cell.colliderMatrix);
Collider.v4.set(voxel.x + 0.5, voxel.y + 0.5, voxel.z + 0.5);
Collider.v1.set(origin.x, origin.y, origin.z);
Collider.v2.copyFrom(direction);
Collider.v1.subtractInPlace(Collider.v4);
Collider.ray.origin.copyFrom(Collider.v1);
Collider.ray.direction.copyFrom(Collider.v2);
Collider.ray.length = 1;
BABYLON.Ray.TransformToRef(Collider.ray, Collider.matrix, Collider.ray);
var pickInfo = Collider.intersectsColliderMesh(colliderMesh, false);
colliderMesh = pickInfo.pickedMesh;
if (pickInfo.hit) {
if (colliderMesh != Collider.fullCollisionMesh && (Math.abs(pickInfo.pickedPoint.x) > 0.5 || Math.abs(pickInfo.pickedPoint.y) > 0.5 || Math.abs(pickInfo.pickedPoint.z) > 0.5)) {
var to0 = BABYLON.Vector3.DistanceSquared(Collider.ray.origin, BABYLON.Vector3.Zero());
var toPP = BABYLON.Vector3.DistanceSquared(Collider.ray.origin, pickInfo.pickedPoint);
if (toPP < to0) {
pickInfo = Collider.ray.intersectsMesh(Collider.fullCollisionMesh, false);
}
}
if (pickInfo.hit) {
var p = BABYLON.Vector3.TransformCoordinates(pickInfo.pickedPoint, Collider.matrix.invert());
p.addInPlace(Collider.v4);
pickInfo.pickedPoint = p;
return { cell, pick: pickInfo };
}
}
return false;
},
grenadeCollidesWithCell: function(origin, direction, voxel, ignoreSoft) {
var cell = Collider.getCellForRay(voxel);
if (!cell)
return false;
colliderMesh = cell.colliderMesh;
Collider.matrix.copyFrom(cell.colliderMatrix);
Collider.v4.set(voxel.x + 0.5, voxel.y + 0.5, voxel.z + 0.5);
Collider.v1.set(origin.x, origin.y, origin.z);
Collider.v2.copyFrom(direction);
var velocity = direction.length();
Collider.v2.normalize().scaleInPlace(10);
Collider.v1.subtractInPlace(Collider.v4);
Collider.ray.origin.copyFrom(Collider.v1);
Collider.ray.direction.copyFrom(Collider.v2);
Collider.ray.length = 1;
BABYLON.Ray.TransformToRef(Collider.ray, Collider.matrix, Collider.ray);
var pickInfo = Collider.intersectsColliderMesh(colliderMesh, false);
colliderMesh = pickInfo.pickedMesh;
if (pickInfo.hit) {
var dist = BABYLON.Vector3.Distance(Collider.ray.origin, pickInfo.pickedPoint);
if (dist <= velocity) {
Collider.matrix.invert();
var p = BABYLON.Vector3.TransformCoordinates(pickInfo.pickedPoint, Collider.matrix);
p.addInPlace(Collider.v4);
pickInfo.pickedPoint = p;
var normal = BABYLON.Vector3.TransformCoordinates(pickInfo.normal, Collider.matrix);
var dot = BABYLON.Vector3.Dot(direction, normal);
return { cell, pick: pickInfo, normal, dot };
} else {
if (!pickInfo.insideMesh)
return false;
var normal = pickInfo.normal;
var pickInfo = Collider.ray.intersectsMesh(Collider.fullCollisionMesh, false);
if (pickInfo.hit) {
Collider.matrix.invert();
var p = BABYLON.Vector3.TransformCoordinates(pickInfo.pickedPoint, Collider.matrix);
p.addInPlace(Collider.v4);
pickInfo.pickedPoint = p;
var normal = pickInfo.getNormal(true, false);
normal = BABYLON.Vector3.TransformCoordinates(normal, Collider.matrix);
var dot = BABYLON.Vector3.Dot(direction, normal);
return { cell, pick: pickInfo, normal, dot };
}
}
}
return false;
},
intersectsColliderMesh: function(colliderMesh2, precise) {
var closestDistance = 1e5;
var closestPick = Collider.ray.intersectsMesh(colliderMesh2, precise);
var closestDot = 0;
var closestNormal = null;
var insideMesh = false;
if (closestPick.hit) {
closestNormal = closestPick.getNormal(true, false);
var dot = BABYLON.Vector3.Dot(Collider.ray.direction, closestNormal);
if (dot > 0)
insideMesh = true;
closestDistance = BABYLON.Vector3.DistanceSquared(Collider.ray.origin, closestPick.pickedPoint);
}
var children = colliderMesh2.getChildMeshes();
for (var i2 = 0; i2 < children.length; i2++) {
var pickInfo = Collider.ray.intersectsMesh(children[i2], precise);
if (pickInfo.hit) {
var distance = BABYLON.Vector3.DistanceSquared(Collider.ray.origin, pickInfo.pickedPoint);
var normal = pickInfo.getNormal(true, false);
var dot = BABYLON.Vector3.Dot(Collider.ray.direction, normal);
if (dot > 0)
insideMesh = true;
if (distance < closestDistance) {
closestDistance = distance;
closestPick = pickInfo;
closestNormal = normal;
if (dot > 0)
insideMesh = true;
}
}
}
closestPick.normal = closestNormal;
closestPick.insideMesh = insideMesh;
return closestPick;
},
rayCollidesWithPlayer: function(origin, direction, proj, radius) {
var fromTeam = proj ? proj.player_.team : null;
var fromId = proj ? proj.player_.id : null;
for (var i2 = 0; i2 < playerLimit; i2++) {
var player = players[i2];
if (player && (player.playing || player.pauseTargetTime > 0) && player.id != fromId && (player.team == 0 || player.team != fromTeam)) {
Collider.ray.origin.copyFrom(origin);
Collider.ray.direction.copyFrom(direction);
Collider.ray.length = 1;
var point = Collider.rayCollidesWithPlayerHelper(Collider.ray, player, radius);
if (point) {
if (proj)
proj.collidesWithPlayer(player, point);
}
}
}
;
return false;
},
// Borrowed (with modifications) from cannon.js' Ray.prototype.intersectsSphere
rayCollidesWithPlayerHelper: function(ray, player, radius) {
var from = ray.origin;
var r = radius || 0.3;
var to = Collider.v1;
to.copyFrom(from).addInPlace(ray.direction);
var position = Collider.v5;
position.set(player.x_, player.y_ + 0.3, player.z_);
var diff = Collider.v2;
diff.copyFrom(ray.origin);
diff.subtractInPlace(position);
var a = BABYLON.Vector3.Dot(ray.direction, ray.direction);
var b2 = 2 * BABYLON.Vector3.Dot(ray.direction, diff);
var c = BABYLON.Vector3.Dot(diff, diff) - r * r;
var delta = Math.pow(b2, 2) - 4 * a * c;
var intersectionPoint = Collider.v3;
var normal = Collider.v4;
if (delta < 0)
return false;
if (delta == 0) {
BABYLON.Vector3.LerpToRef(from, to, delta, intersectionPoint);
intersectionPoint.subtractToRef(position, normal);
normal.normalize();
return normal;
} else {
var d1 = (-b2 - Math.sqrt(delta)) / (2 * a);
var d2 = (-b2 + Math.sqrt(delta)) / (2 * a);
if (d1 >= 0 && d1 <= 1) {
BABYLON.Vector3.LerpToRef(from, to, d1, intersectionPoint);
intersectionPoint.subtractToRef(position, normal);
normal.normalize();
return normal;
}
return false;
}
}
};
var Collision = class _Collision {
static init() {
_Collision.bvh = new BVH3();
}
static pointCollidesWithStructure(point) {
var bb = _Collision.box;
bb.minimumWorld.copyFrom(point);
bb.maximumWorld.copyFrom(point);
let collides = false;
_Collision.bvh.getObjects(bb, (theCollider) => {
if (_Collision.pointCollidesWithBox(point, theCollider))
collides = true;
});
return collides;
}
static pointCollidesWithBox(point, box) {
var pos = _Collision.v3;
var iMatrix = _Collision.mtx2;
pos.copyFrom(point);
pos.subtractInPlace(box.position);
box.matrix.invertToRef(iMatrix);
BABYLON.Vector3.TransformNormalToRef(pos, iMatrix, pos);
if (pos.x >= box.minimumWorld.x && pos.x <= box.maximumWorld.x && pos.y >= box.minimumWorld.y && pos.y <= box.maximumWorld.y && pos.z >= box.minimumWorld.z && pos.z <= box.maximumWorld.z) {
return true;
}
return false;
}
static sphereCollidesWithStructure(center, rad, res, norm) {
var bb = _Collision.box;
var resolve = _Collision.v1;
var normal = _Collision.v2;
bb.minimumWorld.copyFrom(center);
bb.minimumWorld.x -= rad;
bb.minimumWorld.y -= rad;
bb.minimumWorld.z -= rad;
bb.maximumWorld.copyFrom(center);
bb.maximumWorld.x += rad;
bb.maximumWorld.y += rad;
bb.maximumWorld.z += rad;
res.copyFromFloats(0, 0, 0);
var collisions = 0;
var collider = false;
_Collision.bvh.getObjects(bb, (theCollider) => {
if (_Collision.sphereCollidesWithBox(center, rad, theCollider, resolve, normal)) {
if (normal.y < -0.707) {
resolve.y = resolve.length();
resolve.x = 0;
resolve.z = 0;
}
if (resolve.length() > res.length()) {
res.copyFrom(resolve);
norm.copyFrom(normal);
collider = theCollider;
}
collisions++;
}
});
if (collisions > 0) {
return collider;
}
return false;
}
static sphereCollidesWithBox(center, rad, box, resolve, normal) {
var pos = _Collision.v3;
var cPoint = _Collision.v4;
var iMatrix = _Collision.mtx2;
pos.copyFrom(center);
pos.subtractInPlace(box.position);
box.matrix.invertToRef(iMatrix);
BABYLON.Vector3.TransformNormalToRef(pos, iMatrix, pos);
BABYLON.Vector3.ClampToRef(pos, box.minimumWorld, box.maximumWorld, cPoint);
var d = BABYLON.Vector3.Distance(pos, cPoint);
if (d < rad) {
cPoint.subtractInPlace(pos);
BABYLON.Vector3.TransformNormalToRef(cPoint, box.matrix, cPoint);
cPoint.addInPlace(center);
cPoint.subtractInPlace(box.position);
BABYLON.Vector3.ClampToRef(cPoint, _Collision.vmin, _Collision.vmax, cPoint);
cPoint.addInPlace(box.position);
var d = BABYLON.Vector3.Distance(center, cPoint);
cPoint.subtractInPlace(center).normalize();
rad *= Math.abs(cPoint.y) * 0.16 + 0.84;
if (d < rad) {
normal.copyFrom(cPoint);
cPoint.scaleInPlace(d - rad - 1e-3);
resolve.copyFrom(cPoint);
return true;
}
}
return false;
}
/*
static rayCollidesWithStructure (origin, direction, res, norm) {
var ray = Collision.ray;
var resolve = Collision.v1;
var normal = Collision.v2;
var collider = false;
ray.origin.copyFrom(origin);
ray.direction.copyFrom(direction);
Collision.bvh.getObjects(bb, theCollider => {
if (Collision.rayCollidesWithBox(origin, direction, theCollider, resolve, normal)) {
if (callback) {
callback(theCollider, hit, normal);
}
collider = theCollider;
}
});
}
static rayCollidesWithBox (origin, direction, box, res, normal) {
var pos = Collision.v3;
var cPoint = Collision.v4;
var iMatrix = Collision.mtx2;
// First, localize position from sphere space to collision box space
pos.copyFrom(origin);
pos.subtractInPlace(box.position);
box.matrix.invertToRef(iMatrix);
BABYLON.Vector3.TransformNormalToRef(pos, iMatrix, pos);
}
*/
static add(collider) {
_Collision.bvh.add(collider);
}
};
Collision.v1 = new BABYLON.Vector3();
Collision.v2 = new BABYLON.Vector3();
Collision.v3 = new BABYLON.Vector3();
Collision.v4 = new BABYLON.Vector3();
Collision.v5 = new BABYLON.Vector3();
Collision.v6 = new BABYLON.Vector3();
Collision.v7 = new BABYLON.Vector3();
Collision.mtx1 = new BABYLON.Matrix();
Collision.mtx2 = new BABYLON.Matrix();
Collision.vmin = new BABYLON.Vector3(-0.5, -0.5, -0.5);
Collision.vmax = new BABYLON.Vector3(0.5, 0.5, 0.5);
Collision.box = new BABYLON.BoundingBox(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
Collision.Type = {
full: 1,
wedge: 2,
iwedge: 4,
aabb: 8,
obb: 16,
ladder: 32
};
Collision.aabbMask = Collision.Type.full | Collision.Type.aabb | Collision.Type.ladder;
var GameOptions = class {
static init() {
this.value = this.getDefaults();
}
static setToDefaults() {
this.value = this.getDefaults();
}
static getDefaults() {
let def = {
gravity: 1,
damage: 1,
healthRegen: 1,
flags: 0,
weaponDisabled: new Array(G.classes.length)
};
def.weaponDisabled.fill(false);
return def;
}
static usingDefaults() {
let defaults = this.getDefaults();
let isDefault = true;
Object.keys(defaults).forEach((key) => {
let v = this.value[key];
if (key === "flags")
v ^= v & GameFlags.locked;
if (v instanceof Array) {
for (let i2 = 0; i2 < v.length; i2++) {
if (v[i2] !== defaults[key][i2]) {
isDefault = false;
return;
}
}
} else {
if (v !== defaults[key]) {
isDefault = false;
return;
}
}
});
return isDefault;
}
static isSelectedWeaponDisabled(classIdx) {
if (this.areAllWeaponsDisabled())
return false;
return this.value.weaponDisabled[classIdx];
}
static areAllWeaponsDisabled() {
if (!this.value)
return false;
return !this.value.weaponDisabled.includes(false);
}
static serialize() {
var out = CommOut.getBuffer();
out.packInt8(CommCode.gameOptions);
out.packInt8(this.value.gravity * 4);
out.packInt8(this.value.damage * 4);
out.packInt8(this.value.healthRegen * 4);
out.packInt8(this.value.flags);
this.value.weaponDisabled.forEach((v) => {
out.packInt8(v ? 1 : 0);
});
return out;
}
static set(val) {
this.value = val;
}
static parse(apply = true) {
let gravity = CommIn.unPackInt8U();
let damage = CommIn.unPackInt8U();
let healthRegen = CommIn.unPackInt8U();
let flags = CommIn.unPackInt8U();
let weaponDisabled = G.classes.map(() => CommIn.unPackInt8U() === 1);
if (apply) {
if (gravity < 1 || gravity > 4)
gravity = 4;
if (damage < 0 || damage > 8)
damage = 4;
if (healthRegen > 16)
healthRegen = 4;
this.value = {
gravity: gravity / 4,
damage: damage / 4,
healthRegen: healthRegen / 4,
flags,
weaponDisabled
};
return true;
}
return false;
}
};
var GameFlags = {
locked: 1,
noTeamChange: 2,
noTeamShuffle: 4
};
var GameActions = {
reset: 1,
pause: 2
};
function Grenade(scene) {
this.dmgTypeId = DmgType.findIndex((el) => el.name === "Grenade");
this.scene = scene;
this.x = 0;
this.y = 0;
this.z = 0;
this.dx = 0;
this.dy = 0;
this.dz = 0;
this.ttl = 0;
this.resting = false;
this.active = false;
this.player_ = null;
this.actor = new GrenadeActor(this);
}
Grenade.v1 = new BABYLON.Vector3();
Grenade.v2 = new BABYLON.Vector3();
Grenade.v3 = new BABYLON.Vector3();
Grenade.v4 = new BABYLON.Vector3();
Grenade.matrix = new BABYLON.Matrix();
Grenade.prototype.update = function() {
if (this.ttl <= 0) {
this.remove();
return;
}
if (!this.resting) {
var pdx2 = this.dx;
var pdy = this.dy;
var pdz2 = this.dz;
var ndx = 0.5 * (this.dx + pdx2);
var ndy = 0.5 * (this.dy + pdy);
var ndz = 0.5 * (this.dz + pdz2);
var vel = Math.length3(ndx, ndy, ndz);
if (!this.collidesWithMap()) {
this.x += ndx;
this.y += ndy;
this.z += ndz;
this.dy -= GameOptions.value.gravity * 0.012;
}
this.dx *= 0.96;
this.dz *= 0.96;
}
this.ttl -= 1;
};
Grenade.prototype.remove = function() {
munitionsManager.grenadePool.recycle(this);
this.actor.remove();
};
Grenade.prototype.collidesWithMap = function() {
Grenade.v1.set(this.x, this.y - 0.07, this.z);
Grenade.v2.set(this.dx, this.dy, this.dz);
Grenade.v3.set(this.dx, this.dy, this.dz);
var res = Collider.rayCollidesWithMap(Grenade.v1, Grenade.v2, Collider.grenadeCollidesWithCell);
if (res) {
if (res.normal.y == 1 && Grenade.v3.length() < 0.05) {
this.resting = true;
} else {
Grenade.v3.subtractInPlace(res.normal.scale(1.6 * res.dot));
this.dx = Grenade.v3.x * 0.98;
this.dy = Grenade.v3.y;
this.dz = Grenade.v3.z * 0.98;
this.actor.bounce();
return res;
}
}
return false;
};
Grenade.prototype.throw = function(player, pos, vec) {
this.player_ = player;
this.x = pos.x;
this.y = pos.y;
this.z = pos.z;
this.dx = vec.x;
this.dy = vec.y;
this.dz = vec.z;
this.ttl = 75;
this.damage = 150;
this.radius = 3;
this.resting = false;
this.active = true;
this.actor.throw();
};
var Gun = class {
constructor(player) {
this.dmgTypeId = 0;
this.player_ = player;
this.scene = this.player_.scene;
this.highPrecision = false;
this.equipTime = 13;
this.stowWeaponTime = 13;
this.accuracy = this.constructor.accuracyMax;
this.shootingAccuracy = this.constructor.accuracyMax;
this.movementAccuracy = this.constructor.accuracyMax;
this.accuracyMax = this.constructor.accuracyMax;
this.accuracyMin = this.constructor.accuracyMin;
this.accuracyLoss = this.constructor.accuracyLoss;
this.accuracyRecover = this.constructor.accuracyRecover;
this.tracer = 0;
this.burstQueue = 0;
this.adsMod = this.constructor.adsMod || 0.5;
this.movementAccuracyMod = this.constructor.movementAccuracyMod || 1;
}
update() {
if (this.burstQueue > 0) {
if (this.burstQueue % this.constructor.burstRof == 0) {
this.fire();
}
this.burstQueue--;
}
if (this.player_.scope && this.player_.scopeDelay === 0) {
this.accuracyMod = this.adsMod;
} else {
this.accuracyMod = 1;
}
let lateralSpeed = Math.length2(this.player_.dx, this.player_.dz) * 14.41;
let verticalSpeed = Math.min(1, Math.abs(this.player_.dy) * 14.41);
let notReady = this.constructor.reloadBloom && this.player_.reloadCountdown > 0 || this.player_.swapWeaponCountdown > 0 || this.player_.grenadeCountdown > 0;
let ads = this.player_.scope && this.player_.scopeDelay === 0;
let factors = lateralSpeed + verticalSpeed + (notReady ? 1 : 0);
let targetAccuracy = factors * this.constructor.accuracyMin;
if (this.movementAccuracy < targetAccuracy) {
this.movementAccuracy = targetAccuracy;
} else {
this.movementAccuracy = Math.max(this.movementAccuracy - this.constructor.accuracyRecover, targetAccuracy);
}
if (ads) {
this.accuracyMax = this.constructor.accuracyMax * this.adsMod;
this.accuracyMin = this.constructor.accuracyMin * this.adsMod;
this.accuracyLoss = this.constructor.accuracyLoss * this.adsMod;
} else {
this.accuracyMax = this.constructor.accuracyMax;
this.accuracyMin = this.constructor.accuracyMin;
this.accuracyLoss = this.constructor.accuracyLoss;
}
this.accuracyRecover = Math.min(this.accuracyRecover + this.constructor.accuracyRecover, this.constructor.accuracyRecover);
let recover = Math.max(this.accuracyRecover, 0);
this.shootingAccuracy = Math.max(this.shootingAccuracy - recover, this.accuracyMax);
this.accuracy = this.movementAccuracy * this.movementAccuracyMod + this.shootingAccuracy;
if (this.constructor.absoluteMinAccuracy) {
this.accuracy = Math.min(this.accuracy, this.constructor.absoluteMinAccuracy);
}
}
collectAmmo() {
this.ammo.store = Math.min(this.ammo.storeMax, this.ammo.store + this.ammo.pickup);
return true;
}
fire() {
var rotMat = BABYLON.Matrix.RotationYawPitchRoll(this.player_.yaw_, this.player_.pitch_, 0);
var forwardMat = BABYLON.Matrix.Translation(0, 0, this.constructor.range);
var dirMat = forwardMat.multiply(rotMat);
var dir = dirMat.getTranslation();
this.shootingAccuracy = Math.min(this.shootingAccuracy + this.accuracyLoss, this.accuracyMin);
this.accuracyRecover = -this.constructor.accuracyRecover * 8;
let spread = this.accuracy;
if (isNaN(spread)) {
spread = 0;
}
if (this.constructor.burst && this.burstQueue <= 0) {
this.burstQueue = (this.constructor.burst - 1) * this.constructor.burstRof;
}
if (this.constructor !== DozenGauge) {
let spreadRnd = spread;
let spreadMat = BABYLON.Matrix.RotationYawPitchRoll(
(this.player_.randomGen_.getFloat() - 0.5) * spreadRnd,
(this.player_.randomGen_.getFloat() - 0.5) * spreadRnd,
(this.player_.randomGen_.getFloat() - 0.5) * spreadRnd
);
dirMat = dirMat.multiply(spreadMat);
}
var dir = dirMat.getTranslation();
var posMat = BABYLON.Matrix.Translation(0, 0.1, 0);
posMat = posMat.multiply(rotMat);
posMat = posMat.add(BABYLON.Matrix.Translation(
this.player_.x_,
this.player_.y_ + 0.3,
this.player_.z_
));
var pos = posMat.getTranslation();
pos.x = Math.floor(pos.x * 256) / 256;
pos.y = Math.floor(pos.y * 256) / 256;
pos.z = Math.floor(pos.z * 256) / 256;
dir.x = Math.floor(dir.x * 256) / 256;
dir.y = Math.floor(dir.y * 256) / 256;
dir.z = Math.floor(dir.z * 256) / 256;
this.ammo.rounds--;
if (this.player_.id == meId)
updateAmmoUi();
this.actor.fire();
this.fireMunitions(pos, dir);
if (--this.tracer < 0) {
this.tracer = this.constructor.tracer;
}
return;
var out = CommOut.getBuffer();
out.packInt8(CommCode.fire);
out.packInt8(this.player_.id);
out.packFloat(pos.x);
out.packFloat(pos.y);
out.packFloat(pos.z);
out.packFloat(dir.x);
out.packFloat(dir.y);
out.packFloat(dir.z);
sendToAll(out);
this.fireMunitions(pos, dir);
}
// Called by stow animation (probably don't want to count on the animation callback)
equip(speed) {
this.player_.weaponIdx = this.player_.equipWeaponIdx;
this.player_.weapon = this.player_.weapons[this.player_.weaponIdx];
this.player_.weapon.actor.equip(speed);
if (this.player_.id == meId)
updateAmmoUi();
this.player_.lastWeaponChange = 0;
}
};
Gun.reloadBloom = true;
Gun.reloadTimeMod = 1;
var Eggk47 = class _Eggk47 extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 30,
capacity: 30,
reload: 30,
store: 240,
storeMax: 240,
pickup: 30
};
this.longReloadTime = 205;
this.shortReloadTime = 160;
this.actor = new Eggk47Actor(this, meshName);
}
fireMunitions(pos, dir) {
Bullet.fire(this.player_, pos, dir, _Eggk47);
}
};
Eggk47.dmgTypeId = DmgType.findIndex((el) => el.name === "Eggk47");
Eggk47.weaponName = "EggK-47";
Eggk47.standardMeshName = "eggk47";
Eggk47.rof = 3;
Eggk47.recoil = 7;
Eggk47.automatic = true;
Eggk47.damage = 20;
Eggk47.totalDamage = 20;
Eggk47.range = 20;
Eggk47.velocity = 1.5;
Eggk47.tracer = 1;
var DozenGauge = class _DozenGauge extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 2,
capacity: 2,
reload: 2,
store: 24,
storeMax: 24,
pickup: 8
};
this.longReloadTime = 155;
this.shortReloadTime = 155;
this.v1 = new BABYLON.Vector3();
this.actor = new DozenGaugeActor(this, meshName);
}
fireMunitions(pos, dir) {
var w = this.accuracy;
var h = w * 0.6;
for (var i2 = 0; i2 < 20; i2++) {
this.v1.set(
dir.x + this.player_.randomGen_.getFloat(-w, w) * _DozenGauge.range,
dir.y + this.player_.randomGen_.getFloat(-h, h) * _DozenGauge.range,
dir.z + this.player_.randomGen_.getFloat(-w, w) * _DozenGauge.range
);
Bullet.fire(this.player_, pos, this.v1, _DozenGauge);
}
}
};
DozenGauge.dmgTypeId = DmgType.findIndex((el) => el.name === "Scrambler");
DozenGauge.weaponName = "Dozen Gauge";
DozenGauge.standardMeshName = "dozenGauge";
DozenGauge.rof = 8;
DozenGauge.recoil = 10;
DozenGauge.automatic = false;
DozenGauge.damage = 8;
DozenGauge.totalDamage = DozenGauge.damage * 20;
DozenGauge.range = 8;
DozenGauge.velocity = 1;
DozenGauge.tracer = 0;
var CSG1 = class _CSG1 extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 15,
// Number of rounds currently loaded
capacity: 15,
// Magazine capacity
reload: 15,
// Number of rounds added per reload
store: 60,
// Number of rounds player is carrying for this weapon
storeMax: 60,
// Maximum number of rounds player can carry
pickup: 15
// Number of rounds added for each ammo drop collected
};
this.hasScope = true;
this.longReloadTime = 225;
this.shortReloadTime = 165;
this.highPrecision = true;
this.actor = new CSG1Actor(this, meshName);
}
fireMunitions(pos, dir) {
Bullet.fire(this.player_, pos, dir, _CSG1);
}
};
CSG1.dmgTypeId = DmgType.findIndex((el) => el.name === "FreeRanger");
CSG1.weaponName = "CSG-1";
CSG1.standardMeshName = "csg1";
CSG1.rof = 13;
CSG1.recoil = 13;
CSG1.automatic = false;
CSG1.damage = 110;
CSG1.totalDamage = 110;
CSG1.range = 50;
CSG1.velocity = 1.75;
CSG1.tracer = 0;
var Cluck9mm = class _Cluck9mm extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 15,
capacity: 15,
reload: 15,
store: 60,
storeMax: 60,
pickup: 15
};
this.longReloadTime = 195;
this.shortReloadTime = 160;
this.actor = new Cluck9mmActor(this, meshName);
}
fireMunitions(pos, dir) {
Bullet.fire(this.player_, pos, dir, _Cluck9mm);
}
};
Cluck9mm.dmgTypeId = DmgType.findIndex((el) => el.name === "Cluck9mm");
Cluck9mm.weaponName = "Cluck 9mm";
Cluck9mm.standardMeshName = "cluck9mm";
Cluck9mm.rof = 4;
Cluck9mm.recoil = 6;
Cluck9mm.automatic = false;
Cluck9mm.damage = 25;
Cluck9mm.totalDamage = 25;
Cluck9mm.range = 15;
Cluck9mm.velocity = 1;
Cluck9mm.tracer = 0;
var RPEGG = class _RPEGG extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 1,
capacity: 1,
reload: 1,
store: 3,
storeMax: 3,
pickup: 1
};
this.hasScope = true;
this.longReloadTime = 170;
this.shortReloadTime = 170;
this.actor = new RPEGGActor(this, meshName);
}
fireMunitions(pos, dir) {
Rocket.fire(this.player_, pos, dir, _RPEGG);
var animLength = 10;
var size = 0.4;
for (var i2 = 0; i2 < 10; i2++) {
var dx = Math.random() * 0.04 - 0.02;
var dy = Math.random() * 0.04 - 0.02;
var dz = Math.random() * 0.04 - 0.02;
addExplosionSprite(explosionSmokeManager, animLength, pos.x, pos.y, pos.z, dx, dy, dz, size, false, 0);
}
}
};
RPEGG.dmgTypeId = DmgType.findIndex((el) => el.name === "Rpegg");
RPEGG.weaponName = "RPEGG";
RPEGG.standardMeshName = "rpegg";
RPEGG.rof = 40;
RPEGG.recoil = 60;
RPEGG.automatic = false;
RPEGG.damage = 140;
RPEGG.radius = 2.75;
RPEGG.totalDamage = RPEGG.damage * RPEGG.radius * 0.5;
RPEGG.range = 45;
RPEGG.minRange = 3;
RPEGG.velocity = 0.4;
var SMG = class _SMG extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 40,
capacity: 40,
reload: 40,
store: 200,
storeMax: 200,
pickup: 40
};
this.longReloadTime = 225;
this.shortReloadTime = 190;
this.actor = new SMGActor(this, meshName);
}
fireMunitions(pos, dir) {
Bullet.fire(this.player_, pos, dir, _SMG);
}
};
SMG.dmgTypeId = DmgType.findIndex((el) => el.name === "Whipper");
SMG.weaponName = "SMEGG";
SMG.standardMeshName = "smg";
SMG.rof = 2;
SMG.recoil = 7;
SMG.automatic = true;
SMG.damage = 15;
SMG.totalDamage = 15;
SMG.range = 20;
SMG.velocity = 1.25;
SMG.tracer = 2;
var M24 = class _M24 extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 1,
capacity: 1,
reload: 1,
store: 20,
storeMax: 20,
pickup: 4
};
this.hasScope = true;
this.longReloadTime = 144;
this.shortReloadTime = 144;
this.actor = new M24Actor(this, meshName);
}
fireMunitions(pos, dir) {
Bullet.fire(this.player_, pos, dir, _M24);
}
};
M24.dmgTypeId = DmgType.findIndex((el) => el.name === "Crackshot");
M24.weaponName = "M2DZ";
M24.standardMeshName = "m24";
M24.rof = 15;
M24.recoil = 20;
M24.automatic = false;
M24.damage = 200;
M24.totalDamage = 15;
M24.range = 60;
M24.velocity = 2;
M24.tracer = 0;
var AUG = class _AUG extends Gun {
constructor(player, meshName) {
super(player);
this.ammo = {
rounds: 24,
capacity: 24,
reload: 24,
store: 150,
storeMax: 150,
pickup: 24
};
this.longReloadTime = 205;
this.shortReloadTime = 160;
this.actor = new AUGActor(this, meshName);
}
fireMunitions(pos, dir) {
Bullet.fire(this.player_, pos, dir, _AUG);
}
};
AUG.dmgTypeId = DmgType.findIndex((el) => el.name === "TriHard");
AUG.weaponName = "TriHard";
AUG.standardMeshName = "aug";
AUG.rof = 15;
AUG.recoil = 18;
AUG.automatic = false;
AUG.movementInstability = 2;
AUG.damage = 20;
AUG.totalDamage = 20;
AUG.range = 20;
AUG.velocity = 1.5;
AUG.tracer = 0;
AUG.burst = 3;
AUG.burstRof = 1800 / 600;
Eggk47.damage = 30;
Eggk47.accuracyMax = 0.03;
Eggk47.accuracyMin = 0.15;
Eggk47.accuracyLoss = 0.05;
Eggk47.accuracyRecover = 0.025;
Eggk47.totalDamage = 30;
DozenGauge.damage = 8.5;
DozenGauge.accuracyMax = 0.14;
DozenGauge.accuracyMin = 0.17;
DozenGauge.accuracyLoss = 0.17;
DozenGauge.accuracyRecover = 0.02;
DozenGauge.totalDamage = 170;
DozenGauge.adsMod = 0.6;
DozenGauge.movementAccuracyMod = 0.2;
CSG1.damage = 105;
CSG1.accuracyMax = 4e-3;
CSG1.accuracyMin = 0.3;
CSG1.accuracyLoss = 0.3;
CSG1.accuracyRecover = 0.025;
CSG1.totalDamage = 105;
RPEGG.accuracyMax = 0.015;
RPEGG.accuracyMin = 0.3;
RPEGG.accuracyLoss = 0.3;
RPEGG.accuracyRecover = 0.02;
RPEGG.absoluteMinAccuracy = 0.3;
SMG.damage = 23;
SMG.accuracyMax = 0.06;
SMG.accuracyMin = 0.19;
SMG.accuracyLoss = 0.045;
SMG.accuracyRecover = 0.05;
SMG.totalDamage = 23;
SMG.adsMod = 0.6;
SMG.movementAccuracyMod = 0.7;
M24.damage = 170;
M24.accuracyMax = 0;
M24.accuracyMin = 0.35;
M24.accuracyLoss = 0.1;
M24.accuracyRecover = 0.023;
M24.totalDamage = 170;
M24.movementAccuracyMod = 0.85;
M24.reloadBloom = false;
M24.reloadTimeMod = 0.8;
Cluck9mm.damage = 26;
Cluck9mm.accuracyMax = 0.035;
Cluck9mm.accuracyMin = 0.15;
Cluck9mm.accuracyLoss = 0.09;
Cluck9mm.accuracyRecover = 0.08;
Cluck9mm.totalDamage = 26;
Cluck9mm.adsMod = 0.8;
Cluck9mm.movementAccuracyMod = 0.6;
AUG.damage = 35;
AUG.accuracyMax = 0.03;
AUG.accuracyMin = 0.15;
AUG.accuracyLoss = 0.04;
AUG.accuracyRecover = 0.03;
AUG.totalDamage = 34;
AUG.adsMod = 0.6;
AUG.movementAccuracyMod = 0.8;
var maps = [{ "filename": "aqueduct", "hash": "28jf33x9icp", "name": "Aqueduct", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "backstage", "hash": "22hccli51v9", "name": "Backstage", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "14" }, { "filename": "bastion", "hash": "1baur79xgrl", "name": "Bastion", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "12" }, { "filename": "bedrock", "hash": "1sas4lnmngy", "name": "Bedrock", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "12" }, { "filename": "biohazard", "hash": "j6fhuow8d5", "name": "BioHazard", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "18" }, { "filename": "blender", "hash": "1m4xadroj52", "name": "Blender", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "14" }, { "filename": "blue", "hash": "1vjawasrx92", "name": "Blue", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "14" }, { "filename": "bridge", "hash": "yhwrty2kdb", "name": "Bridge", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "6" }, { "filename": "cash", "hash": "2b6jxldu9yt", "name": "Cash", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "castle", "hash": "1ohl8pdid1j", "name": "Castle", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "12" }, { "filename": "castleArena", "hash": "10fqurvpovc", "name": "Castle Arena", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "8" }, { "filename": "catacombs", "hash": "26lvz7mtm7c", "name": "Catacombs", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "chickenItza", "hash": "1cghvq86la6", "name": "Chicken Itza", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "18" }, { "filename": "cluckgrounds", "hash": "11zqosithhn", "name": "Cluckgrounds", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "16" }, { "filename": "crowsnest", "hash": "19mwnq2te9r", "name": "Crowsnest", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "8" }, { "filename": "deathpit", "hash": "1b0r2blywas", "name": "Death Pit", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "12" }, { "filename": "dirt", "hash": "1ett2uygvbj", "name": "Dirt", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "dirt2", "hash": "ezol41g8ub", "name": "Dirt 2", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "dirtbase", "hash": "1tuuh5gfnef", "name": "Dirt Base", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "10" }, { "filename": "downfall", "hash": "xo8wjszh6w", "name": "Downfall", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "18" }, { "filename": "duelPyramidLG", "hash": "k0rzn9mndm", "name": "Duel Pyramid Low-Grav", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "6" }, { "filename": "eggcrates", "hash": "25340eipbpz", "name": "Eggcrates", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "6" }, { "filename": "enchanted", "hash": "pflyna5tq5", "name": "Enchanted", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "16" }, { "filename": "exposure", "hash": "umpd4wdao3", "name": "Exposure", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "18" }, { "filename": "feedlot", "hash": "1c6rortschf", "name": "Feedlot", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "16" }, { "filename": "field", "hash": "13pwzx5f1md", "name": "Field", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "10" }, { "filename": "fortFlip", "hash": "1d6f8ucy19b", "name": "Fort Flip", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "fourQuarters", "hash": "1e0dogzazf9", "name": "Four Quarters", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "10" }, { "filename": "growler", "hash": "2jf082miup", "name": "Growler", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "12" }, { "filename": "haunted", "hash": "3ygypcx8ew", "name": "Haunted", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "16" }, { "filename": "helix", "hash": "1aqp7c8qnlt", "name": "Helix", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "hydro", "hash": "1llnw4tf0co", "name": "Hydro", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "18" }, { "filename": "jailbreak", "hash": "g01fcj8gxy", "name": "Jail Break", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "14" }, { "filename": "jinx", "hash": "277lyg65e23", "name": "Jinx", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "junction", "hash": "68j04g1gq8", "name": "Junction", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "kingsCourt", "hash": "h6bc14b784", "name": "King's Court", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "mansion", "hash": "186j0mb9hp4", "name": "Mansion", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "moonbase", "hash": "1w5mr9jx0ba", "name": "Moonbase", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "18" }, { "filename": "mudGulch", "hash": "kl9pir6oov", "name": "Mud Gulch", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "14" }, { "filename": "outer", "hash": "2d3t2xcj40e", "name": "Outer Reach", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "overcooked", "hash": "25mleaa2j5o", "name": "Overcooked", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "12" }, { "filename": "palaceSiege", "hash": "aevymuxzca", "name": "Palace Siege", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "14" }, { "filename": "quarry", "hash": "1baedxtwz8v", "name": "Quarry", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "14" }, { "filename": "raceway", "hash": "zo3cplgmyn", "name": "Raceway", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "rameses", "hash": "ml96x9mcob", "name": "Rameses", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "16" }, { "filename": "rats", "hash": "1likbl80ern", "name": "Rats", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "rivals", "hash": "113nhmlw9w7", "name": "Rivals", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "6" }, { "filename": "road", "hash": "7ag0z4cpk5", "name": "Road", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "14" }, { "filename": "ruins", "hash": "1vjenhltpg2", "name": "Ruins", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "scales", "hash": "1lcm4phbzei", "name": "Scales", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "shadyglen", "hash": "1fn5xi68nmr", "name": "Shady Glen", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "12" }, { "filename": "shellville", "hash": "alpo4cn3zq", "name": "Shellville", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "16" }, { "filename": "shipyard", "hash": "19avbwnpbg9", "name": "Shipyard", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "skyScratcher", "hash": "1xfilhzsds3", "name": "Sky Scratcher", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "spaceFactory", "hash": "2agr2lfddck", "name": "Space Factory", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "10" }, { "filename": "spacearena", "hash": "241xmvj0ufg", "name": "Space Arena", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "14" }, { "filename": "sparta", "hash": "5xpceip54g", "name": "Sparta", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "both", "numPlayers": "18" }, { "filename": "spellbound", "hash": "182fexvavx9", "name": "Spellbound", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "12" }, { "filename": "stage", "hash": "21yhx7f42by", "name": "Stage", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "staxarena", "hash": "19t57lht2nr", "name": "Stax Arena", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "6" }, { "filename": "teggtris", "hash": "uumhnkbjux", "name": "Teggtris", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "temple", "hash": "1i5f45tlan5", "name": "Temple", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "both", "numPlayers": "18" }, { "filename": "timetwist", "hash": "3q5gis7qeh", "name": "Timetwist", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "trainyard", "hash": "smve6npq9w", "name": "Trainyard", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "treefort", "hash": "1smqjmht64q", "name": "Tree Fort", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": false }, "availability": "private", "numPlayers": "6" }, { "filename": "twoTowers", "hash": "9qzxjqr1d7", "name": "Two Towers", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "vert", "hash": "1vdspatyhc4", "name": "Vert", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "12" }, { "filename": "wimble", "hash": "jmjb04b954", "name": "Wimble", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }, { "filename": "wreckage", "hash": "1u7p7s6mepg", "name": "Wreckage", "modes": { "FFA": true, "Teams": true, "Spatula": true, "King": true }, "availability": "private", "numPlayers": "18" }];
Math.PI2 = Math.PI * 2;
Math.PI90 = Math.PI / 2;
Math.mod = function(n, m) {
var remain = n % m;
return remain >= 0 ? remain : remain + m;
};
Math.length2 = function(x, y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
};
Math.length3 = function(x, y, z) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2));
};
Math.capVector2 = function(vec, len) {
var l = Math.length2(vec.x, vec.y);
if (l > len) {
vec.x *= len / l;
vec.y *= len / l;
}
return vec;
};
Math.capVector3 = function(vec, len) {
var l = Math.length3(vec.x, vec.y, vec.z);
if (l > len) {
vec.x *= len / l;
vec.y *= len / l;
vec.z *= len / l;
}
return vec;
};
Math.normalize2 = function(vec, len) {
len = len || 1;
var l = Math.length2(vec.x, vec.y);
vec.x *= len / l;
vec.y *= len / l;
return vec;
};
Math.normalize3 = function(vec, len) {
len = len || 1;
var l = Math.length3(vec.x, vec.y, vec.z);
vec.x *= len / l;
vec.y *= len / l;
vec.z *= len / l;
return vec;
};
Math.clamp = function(v, min, max) {
return Math.max(Math.min(v, max), min);
};
Math.radAdd = function(a, b2) {
return Math.floor(Math.mod(a + b2, Math.PI2) * 8192) / 8192;
};
Math.radSub = function(a, b2) {
return Math.floor(Math.mod(a - b2, Math.PI2) * 8192) / 8192;
};
Math.radRange = function(n) {
return Math.mod(n, Math.PI2);
};
Math.radDifference = function(fromAngle, toAngle) {
var diff = (fromAngle - toAngle + Math.PI) % Math.PI2 - Math.PI;
diff = diff < -Math.PI ? diff + Math.PI2 : diff;
return diff;
};
Math.cardVals = [0, Math.PI90, Math.PI, Math.PI90 * 3];
Math.cardToRad = function(card) {
return Math.cardVals[card];
};
Math.randomInt = function(low, high) {
return Math.floor(Math.random() * (high - low) + low);
};
Math.diff = function(a, b2, threshold) {
if (a < b2)
return threshold - a + b2;
return a - b2;
};
function SeededRandom() {
this.seed = 100;
}
SeededRandom.prototype.setSeed = function(seed) {
this.seed = seed;
};
SeededRandom.prototype.getFloat = function(min, max) {
min = min || 0;
max = max || 1;
this.seed = (this.seed * 9301 + 49297) % 233280;
var rnd = this.seed / 233280;
return min + rnd * (max - min);
};
SeededRandom.prototype.getInt = function(min, max) {
return Math.floor(this.getFloat(min, max));
};
var Ease = {
// no easing, no acceleration
linear: function(t) {
return t;
},
// accelerating from zero velocity
inQuad: function(t) {
return t * t;
},
// decelerating to zero velocity
outQuad: function(t) {
return t * (2 - t);
},
// acceleration until halfway, then deceleration
inOutQuad: function(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
},
// accelerating from zero velocity
inCubic: function(t) {
return t * t * t;
},
// decelerating to zero velocity
outCubic: function(t) {
return --t * t * t + 1;
},
// acceleration until halfway, then deceleration
inOutCubic: function(t) {
return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
},
// accelerating from zero velocity
inQuart: function(t) {
return t * t * t * t;
},
// decelerating to zero velocity
outQuart: function(t) {
return 1 - --t * t * t * t;
},
// acceleration until halfway, then deceleration
inOutQuart: function(t) {
return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;
},
// accelerating from zero velocity
inQuint: function(t) {
return t * t * t * t * t;
},
// decelerating to zero velocity
outQuint: function(t) {
return 1 + --t * t * t * t * t;
},
// acceleration until halfway, then deceleration
inOutQuint: function(t) {
return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;
}
};
var MeleeWeapon = class _MeleeWeapon {
constructor(player) {
this.player_ = player;
this.scene = this.player_.scene;
this.collisionCountdown = 0;
this.dmgTypeId = DmgType.findIndex((el) => el.name === "Melee");
if (player.actor) {
this.actor = new MeleeWeaponActor(this, this.player_.meleeItem.item_data.meshName);
}
this.dir = new BABYLON.Vector3();
}
attack() {
this.collisionCountdown = 5;
}
checkCollisions() {
var rotMat = BABYLON.Matrix.RotationYawPitchRoll(this.player_.yaw_, this.player_.pitch_, 0);
var forwardMat = BABYLON.Matrix.Translation(0, 0, 0.8);
var dirMat = forwardMat.multiply(rotMat);
this.dir = dirMat.getTranslation();
_MeleeWeapon.v1.set(this.player_.x_ - this.dir.x * 0.25, this.player_.y_ - this.dir.y * 0.25 + 0.3, this.player_.z_ - this.dir.z * 0.25);
Collider.rayCollidesWithPlayer(_MeleeWeapon.v1, this.dir, this, 0.475);
}
collidesWithPlayer(player) {
let damage = 40;
if (this.player_.activeShellStreaks & ShellStreak.EggBreaker) {
damage = 255;
}
hitPlayer(player, this, damage, this.dir.x, this.dir.z);
}
update() {
if (this.collisionCountdown > 0) {
if (--this.collisionCountdown === 0) {
this.checkCollisions();
}
}
}
};
MeleeWeapon.v1 = new BABYLON.Vector3();
MeleeWeapon.v2 = new BABYLON.Vector3();
function MunitionsManager(scene) {
this.bulletPool = new Pool(function() {
return new Bullet(scene);
}, 200);
this.rocketPool = new Pool(function() {
return new Rocket(scene);
}, 20);
this.grenadePool = new Pool(function() {
return new Grenade(scene);
}, 10);
}
MunitionsManager.prototype.updateLogic = function() {
this.bulletPool.forEachActive(function(bullet) {
bullet.update();
});
this.rocketPool.forEachActive(function(rocket) {
rocket.update();
});
this.grenadePool.forEachActive(function(grenade) {
grenade.update();
});
};
MunitionsManager.prototype.updateActors = function(delta) {
this.bulletPool.forEachActive(function(bullet) {
bullet.actor.update(delta);
});
this.rocketPool.forEachActive(function(rocket) {
rocket.actor.update(delta);
});
this.grenadePool.forEachActive(function(grenade) {
grenade.actor.update(delta);
});
};
MunitionsManager.prototype.removeAll = function() {
this.bulletPool.forEachActive(function(bullet) {
bullet.remove();
});
this.rocketPool.forEachActive(function(rocket) {
rocket.remove();
});
this.grenadePool.forEachActive(function(grenade) {
grenade.remove();
});
};
MunitionsManager.prototype.throwGrenade = function(player, pos, vec) {
var grenade = this.grenadePool.retrieve();
grenade.throw(player, pos, vec);
};
MunitionsManager.prototype.getMapIntersectionPoint = function(proj, res) {
if (res && !mapMeshes[res.cell.idx].softness && res.cell && res.cell.idx) {
var mapMesh2 = mapMeshes[res.cell.idx];
var ray = new BABYLON.Ray(
new BABYLON.Vector3(proj.x - proj.dx - res.x - 0.5, proj.y - proj.dy - res.y - 0.5, proj.z - proj.dz - res.z - 0.5),
new BABYLON.Vector3(proj.dx * 2, proj.dy * 2, proj.dz * 2),
1
);
mapMesh2.rotation.x = res.cell.rx;
mapMesh2.rotation.y = res.cell.ry;
mapMesh2.rotation.z = res.cell.rz;
var pickInfo = ray.intersectsMesh(mapMesh2, false);
if (pickInfo.hit) {
var ofs = new BABYLON.Vector3(-proj.dx, -proj.dy, -proj.dz).normalize().scale(5e-3);
return {
x: pickInfo.pickedPoint.x + res.x + 0.5 + ofs.x,
y: pickInfo.pickedPoint.y + res.y + 0.5 + ofs.y,
z: pickInfo.pickedPoint.z + res.z + 0.5 + ofs.z
};
}
}
return false;
};
var CONTROL = {
// Movement controls bitmask
up: 1,
down: 2,
left: 4,
right: 8,
jump: 16,
fire: 32,
melee: 64,
scope: 128,
// The rest of these are outside the 8-bit range (1-128) of network control codes
ascend: 256,
descend: 512
};
G.classes = [
{ name: "Soldier", weapon: Eggk47 },
{ name: "Scrambler", weapon: DozenGauge },
{ name: "Free Ranger", weapon: CSG1 },
{ name: "Eggsploder", weapon: RPEGG },
{ name: "Whipper", weapon: SMG },
{ name: "Crackshot", weapon: M24 },
{ name: "TriHard", weapon: AUG }
];
var stateBufferSize = 256;
function Player(data2, scene) {
this.id = data2.id_;
this.uniqueId = data2.uniqueId_;
this.name = data2.name_;
this.normalName = data2.normalName_;
this.safeName = data2.safeName_;
this.charClass = data2.charClass_;
this.team = data2.team_;
this.primaryWeaponItem = data2.primaryWeaponItem_;
this.secondaryWeaponItem = data2.secondaryWeaponItem_;
this.shellColor = data2.shellColor_;
this.hatItem = data2.hatItem_;
this.stampItem = data2.stampItem_;
this.grenadeItem = data2.grenadeItem_;
this.meleeItem = data2.meleeItem_;
this.x_ = data2.x_;
this.y_ = data2.y_;
this.z_ = data2.z_;
this.dx = data2.dx_;
this.dy = data2.dy_;
this.dz = data2.dz_;
this.controlKeys = data2.controlKeys;
this.yaw_ = data2.yaw_;
this.pitch_ = data2.pitch_;
this.speed = 0;
this.scope = false;
this.scopeDelay = 0;
this.primaryWeaponDisabled = false;
this.score = data2.score_;
this.totalKills = 0;
this.totalDeaths = 0;
this.bestGameStreak = data2.bestGameStreak_;
this.bestOverallStreak = data2.bestOverallStreak_;
this.stats = {
streak: data2.stats_.streak,
kills: data2.stats_.kills,
killsCluck9mm: data2.stats_.killsCluck9mm,
killsGrenade: data2.stats_.killsGrenade,
killsRpegg: data2.stats_.killsRpegg,
killsEggk47: data2.stats_.killsEggk47,
killsScrambler: data2.stats_.killsScrambler,
killsFreeRanger: data2.stats_.killsFreeRanger,
killsWhipper: data2.stats_.killsWhipper,
killsCrackshot: data2.stats_.killsCrackshot,
killsTriHard: data2.stats_.killsTriHard,
killsMelee: data2.stats_.killsMelee,
killsPrivate: data2.stats_.killsPrivate,
killsPublic: data2.stats_.killsPublic,
killsKing: data2.stats_.killsKing,
killsSpatula: data2.stats_.killsSpatula,
killsTeams: data2.stats_.killsTeams,
killsFFA: data2.stats_.killsFFA,
deaths: data2.stats_.deaths,
deathsCluck9mm: data2.stats_.deathsCluck9mm,
deathsGrenade: data2.stats_.deathsGrenade,
deathsRpegg: data2.stats_.deathsRpegg,
deathsEggk47: data2.stats_.deathsEggk47,
deathsScrambler: data2.stats_.deathsScrambler,
deathsFreeRanger: data2.stats_.deathsFreeRanger,
deathsWhipper: data2.stats_.deathsWhipper,
deathsCrackshot: data2.stats_.deathsCrackshot,
deathsTriHard: data2.stats_.deathsTriHard,
deathsMelee: data2.stats_.deathsMelee,
deathsPrivate: data2.stats_.deathsPrivate,
deathsPublic: data2.stats_.deathsPublic,
deathsKing: data2.stats_.deathsKing,
deathsSpatula: data2.stats_.deathsSpatula,
deathsTeams: data2.stats_.deathsTeams,
deathsFFA: data2.stats_.deathsFFA,
kotcCaptured: data2.stats_.kotcCaptured,
kotcWins: data2.stats_.kotcWins
};
this.gameData = data2.gameData_;
this.shield = data2.shield_;
this.hp_ = data2.hp_;
this.playing = data2.playing_;
this.weaponIdx = data2.weaponIdx_;
this.upgradeProductId = data2.upgradeProductId_;
this.mobileMultiplier = 1;
this.isGameOwner = data2.isGameOwner_;
this.capturing = false;
this.activeShellStreaks = data2.activeShellStreaks_;
this.adminRoles = data2.adminRoles_;
this.muted = data2.muted_;
this.scene = scene;
this.corrected = { dx: 0, dy: 0, dz: 0, pitch_: 0, yaw_: 0 };
this.corrections = 0;
this.totalCorrections = 2;
this.resetCountdowns();
this.equipWeaponIdx = this.weaponIdx;
this.grenadeCount = 1;
this.grenadeCapacity = 3;
this.lastWeaponChange = 0;
this.jumpQueued = 0;
this.jumping = false;
this.onGround = 4;
this.climbing = false;
this.bobble = 0;
this.hardBoiledValue = 0;
this.eggBreakerValue = 0;
this.stateIdx = 0;
this.clientStateIdx = 0;
this.serverStateIdx = 0;
this.respawnTargetTime = 0;
this.pauseTargetTime = 0;
this.ready = false;
this.chatLines = 0;
this.respawnQueued = false;
this.canTakeTeamBonus = true;
this.changingCharacter = false;
this.lastDamageTakenType = 0;
this.lastDamageGivenType = 0;
this.lastDmgType = 0;
this.damageMod = data2.damageMod_;
this.abBucket = data2.abBucket_;
this.actor = new PlayerActor(this);
this.changeWeaponLoadout(this.primaryWeaponItem, this.secondaryWeaponItem);
this.stateBuffer = [];
this.resetStateBuffer();
this.randomGen_ = new SeededRandom();
this.social = data2.social_;
this.hideBadge = data2.hideBadge_;
}
Player.v1 = new BABYLON.Vector3();
Player.v2 = new BABYLON.Vector3();
Player.v3 = new BABYLON.Vector3();
Player.v4 = new BABYLON.Vector3();
Player.v5 = new BABYLON.Vector2();
Player.v6 = new BABYLON.Vector2();
Player.v7 = new BABYLON.Vector3();
Player.v8 = new BABYLON.Vector3();
Player.ray = new BABYLON.Ray();
Player.matrix = new BABYLON.Matrix();
Player.prototype.changeWeaponLoadout = function(primaryWeaponItem, secondaryWeaponItem) {
if (this.weapons) {
this.weapons[0].actor.dispose();
this.weapons[1].actor.dispose();
this.meleeWeapon.actor.dispose();
}
this.meleeWeapon = new MeleeWeapon(this);
this.primaryWeaponItem = primaryWeaponItem;
this.secondaryWeaponItem = secondaryWeaponItem;
this.weapons = [
primaryWeaponItem.instantiateNew(this),
secondaryWeaponItem.instantiateNew(this)
];
this.weapon = this.weapons[this.weaponIdx];
this.weapon.actor.equip();
};
Player.prototype.update_ = function(resim) {
var dx = 0;
var dy = 0;
var dz = 0;
if (!resim && this.id == meId) {
this.controlKeys = controlKeys;
}
if (!this.actor || this.id != meId) {
var idx = this.stateIdx;
idx = Math.min(idx, FramesBetweenSyncs - 1);
this.controlKeys = this.stateBuffer[idx].controlKeys;
this.yaw_ = this.stateBuffer[idx].yaw_;
this.pitch_ = this.stateBuffer[idx].pitch_;
this.stateBuffer[idx].controlKeys = 0;
}
var state = this.stateBuffer[this.stateIdx];
state.controlKeys = this.controlKeys;
state.yaw_ = this.yaw_;
state.pitch_ = this.pitch_;
if (this.controlKeys & CONTROL.left) {
dx -= Math.cos(this.yaw_);
dz += Math.sin(this.yaw_);
}
if (this.controlKeys & CONTROL.right) {
dx += Math.cos(this.yaw_);
dz -= Math.sin(this.yaw_);
}
if (this.controlKeys & CONTROL.up) {
if (this.climbing) {
dy += 1;
} else {
dx += Math.sin(this.yaw_);
dz += Math.cos(this.yaw_);
}
}
if (this.controlKeys & CONTROL.down) {
if (this.climbing) {
dy -= 1;
} else {
dx -= Math.sin(this.yaw_);
dz -= Math.cos(this.yaw_);
}
}
if (this.controlKeys & CONTROL.jump) {
this.jumpQueued = 10;
this.controlKeys ^= this.controlKeys & CONTROL.jump;
if (this.id == meId) {
controlKeys ^= controlKeys & CONTROL.jump;
}
}
if (this.controlKeys & CONTROL.scope) {
if (!this.scope)
this.scopeIn();
} else {
if (this.scope)
this.scopeOut();
}
if (this.jumpQueued > 0) {
this.jumpQueued--;
this.jump();
}
let ads = this.scope && this.scopeDelay === 0;
if (this.climbing) {
this.setJumping(false);
var pdy = this.dy;
if (this.corrections) {
pdy += this.corrected.dy / this.totalCorrections;
this.corrections--;
}
this.dy += dy * 0.028;
var ndy = 0.5 * (this.dy + pdy);
this.y_ += ndy;
this.dy *= 0.5;
if (Math.floor(this.y_) >= map.height) {
this.climbing = false;
}
this.move(0, ndy, 0);
} else {
var deltaVector = new BABYLON.Vector3(dx, dy, dz).normalize();
if (ads) {
deltaVector.x *= 0.5;
deltaVector.z *= 0.5;
}
this.dx += deltaVector.x * 0.025;
this.dz += deltaVector.z * 0.025;
this.dy -= GameOptions.value.gravity * 0.012;
this.dy = Math.max(-0.29, this.dy);
var oldPos = Player.v4;
oldPos.copyFromFloats(this.x_, this.y_, this.z_);
this.move(this.dx, this.dy, this.dz);
this.dx = this.x_ - oldPos.x;
this.dy = this.y_ - oldPos.y;
this.dz = this.z_ - oldPos.z;
if (this.onGround && this.dy > 0) {
var n = 1 - Player.v7.copyFromFloats(this.dx, this.dy, this.dz).normalize().y * 0.5;
this.dx *= n;
this.dz *= n;
}
if (!resim && this.corrections) {
pdy = 0;
pdx = this.corrected.dx / this.totalCorrections;
if (this.climbing)
pdy = this.corrected.dy / this.totalCorrections;
pdz = this.corrected.dz / this.totalCorrections;
this.corrections--;
this.move(pdx, pdy, pdz);
}
}
if (!resim) {
if (this.shield > 0 && this.playing) {
this.shield -= 2;
if (dx != 0 || dy != 0 || this.shield <= 0) {
this.disableShield();
}
}
this.scopeDelay = Math.max(0, this.scopeDelay - 1);
this.lastWeaponChange++;
var speed = Math.max(0, Math.length3(this.dx, this.dy, this.dz) - 0.012);
this.speed = speed;
if (this.climbing || this.jumping)
speed *= 2;
this.bobble = (this.bobble + (speed + 0.01) * 7) % Math.PI2;
if (this.weapon)
this.weapon.update();
this.meleeWeapon.update();
if (this.meleeCountdown > 0) {
if (--this.meleeCountdown === 0) {
this.swapWeaponCountdown = this.weapon.equipTime * 0.5;
this.actor.wieldGun();
if (this.id === me) {
reticle.show();
}
}
}
if (this.hp_ > 0)
this.hp_ = Math.min(100, this.hp_ + 0.1 * GameOptions.value.healthRegen);
if (this.swapWeaponCountdown > 0) {
this.swapWeaponCountdown--;
if (this.swapWeaponCountdown <= 0) {
if (this.id == meId) {
reticle.show();
}
}
}
if (this.reloadCountdown > 0) {
this.lastWeaponChange = 0;
this.reloadCountdown -= 2;
if (this.reloadCountdown <= 0) {
this.reloadCountdown = 0;
this.reloaded();
}
}
if (this.rofCountdown > 0) {
this.rofCountdown = Math.max(this.rofCountdown - 1, 0);
}
if (this.recoilCountdown > 0) {
this.recoilCountdown = Math.max(this.recoilCountdown - 2, 0);
}
if (this.grenadeCountdown > 0) {
this.grenadeCountdown -= 2;
}
if (this.id == meId) {
if (this.triggerPulled) {
this.fire();
}
if (this.activeShellStreaks & ShellStreak.EggBreaker) {
this.eggBreakerValue = Math.max(0, this.eggBreakerValue - 1);
}
var val = Math.floor(this.eggBreakerValue / 30);
var el = document.getElementById("eggBreakerTimer");
if (val != parseInt(el.innerText)) {
el.innerText = val;
}
}
this.stateIdx = Math.mod(this.stateIdx + 1, stateBufferSize);
var state = this.stateBuffer[this.stateIdx];
this.saveState(state);
if (ws && this.id == meId && me.stateIdx % FramesBetweenSyncs == 0 && ws.readyState == ws.OPEN && me.playing && !freezeFrame) {
serverSync();
}
}
this.dx *= 0.64;
this.dz *= 0.64;
if (this.climbing)
this.dy *= 0.64;
if (!this.actor || this.id != meId) {
if (this.reloadsQueued > 0)
this.reload();
if (this.weaponSwapsQueued > 0)
this.swapWeapon(this.equipWeaponIdx);
}
if (!this.actor && this.y_ < -10) {
this.die();
let dmgType = DmgType.findIndex((el2) => el2.name === "Fall");
metaGame.scoreKill(this, this);
var out = CommOut.getBuffer();
out.packInt8(CommCode.die);
out.packInt8(this.id);
out.packInt8(this.id);
out.packInt8(8);
out.packInt8(dmgType);
out.packInt8(dmgType);
sendToAll(out);
}
};
Player.prototype.saveState = function(state) {
state.x_ = this.x_;
state.y_ = this.y_;
state.z_ = this.z_;
state.dx = this.dx;
state.dy = this.dy;
state.dz = this.dz;
state.jumping = this.jumping;
state.climbing = this.climbing;
state.weaponIdx = this.weaponIdx;
state.rounds = this.weapon.ammo.rounds;
state.store = this.weapon.ammo.store;
};
Player.prototype.move = function(ndx, ndy, ndz) {
var position = Player.v1;
var velocity = Player.v8;
var collisionResolve = Player.v2;
var normal = Player.v3;
var cell;
this.onGround = Math.max(--this.onGround, 0);
this.y_ += 0.31;
velocity.copyFromFloats(ndx, ndy, ndz);
Math.capVector3(velocity, 0.29);
position.copyFromFloats(this.x_, this.y_, this.z_);
position.addInPlace(velocity);
position.x = Math.clamp(position.x, 0.1, map.width - 0.1);
position.z = Math.clamp(position.z, 0.1, map.depth - 0.1);
for (var i2 = 0; i2 < 8; i2++) {
var collider = Collision.sphereCollidesWithStructure(position, 0.31, collisionResolve, normal);
if (collider) {
if (normal.y < -0.707) {
this.onGround = 4;
}
if (!this.climbing) {
if (collider.colliderType & Collision.Type.ladder) {
this.tryToClimbLadder(collider, normal);
}
}
position.addInPlace(collisionResolve);
if (this.onGround) {
if (this.jumping) {
this.setJumping(false);
this.dy = 0;
} else {
if (this.controlKeys & CONTROL.down) {
this.climbing = false;
}
}
}
} else {
break;
}
}
if (i2 == 8) {
velocity.scaleInPlace(0.9);
position.subtractInPlace(velocity);
}
this.x_ = position.x;
this.y_ = position.y;
this.z_ = position.z;
if (this.climbing && (!this.actor || this.id == meId)) {
var cx = this.climbX;
var cz = this.climbZ;
this.climbing = false;
this.capturing = false;
cell = getMapCellAt(cx, Math.floor(this.y_ - 0.25), cz);
if (cell && Math.floor(cell.ry / Math.PI90) == this.climbRY && cell.mesh && cell.mesh.colliderType == "ladder") {
this.climbing = true;
}
cell = getMapCellAt(cx, Math.floor(this.y_ + 0.25), cz);
if (cell && Math.floor(cell.ry / Math.PI90) == this.climbRY && cell.mesh && cell.mesh.colliderType == "ladder") {
this.climbing = true;
}
} else {
var cx = Math.floor(this.x_);
var cy = Math.floor(this.y_);
var cz = Math.floor(this.z_);
if (this.playing) {
cell = getMapCellAt(cx, cy, cz);
if (cell) {
var zone = cell.zone;
if (zone) {
} else {
this.capturing = false;
}
}
}
cell = getMapCellAt(cx, Math.floor(this.y_ - 0.5), cz);
if (cell) {
mesh = cell.mesh;
if (mesh) {
if (mesh.shortName == "jump-pad" && this.canJump() && Math.length2(cx + 0.5 - this.x_, cz + 0.5 - this.z_) < 0.3) {
this.y_ += 0.26;
this.setJumping(true);
}
}
}
}
if (this.y_ < 0) {
}
this.y_ -= 0.31;
};
Player.prototype.tryToClimbLadder = function(collide, normal) {
if (!(this.controlKeys & CONTROL.up))
return;
if (Math.abs(collide.position.y - (this.y_ + 0.18)) > 0.9)
return;
var h = Math.round(this.yaw_ / Math.PI90) % 4;
var ry = collide.cell.ry;
if (h != ry && (h + 2) % 4 != ry)
return;
var resolve = Player.v5.set(normal.x, normal.z).normalize();
var delta = Player.v6.set(Math.cos(this.yaw_), -Math.sin(this.yaw_));
var dot = BABYLON.Vector2.Dot(delta, resolve);
if (Math.abs(dot) < 0.4) {
this.climbing = true;
this.climbX = Math.clamp(Math.floor(collide.position.x), 0, map.width - 1);
this.climbZ = Math.clamp(Math.floor(collide.position.z), 0, map.depth - 1);
this.climbRY = collide.cell.ry;
this.dy = 0;
this.setJumping(false);
}
};
Player.prototype.scopeIn = function() {
if (this.isAtReady()) {
if (this.weapon.actor) {
this.weapon.actor.restPose();
}
this.scope = true;
this.scopeDelay = 7;
}
};
Player.prototype.scopeOut = function() {
this.scope = false;
};
Player.prototype.disableShield = function() {
this.shield = 0;
this.actor.bodyMesh_.renderOverlay = false;
this.actor.hands.renderOverlay = false;
};
Player.prototype.enableShield = function() {
this.shield = 120;
this.actor.bodyMesh_.overlayColor = Player.OverlayColor.green;
this.actor.hands.overlayColor = Player.OverlayColor.green;
this.actor.bodyMesh_.renderOverlay = true;
this.actor.hands.renderOverlay = true;
};
Player.prototype.resetStateBuffer = function() {
for (var i2 = 0; i2 < stateBufferSize; i2++) {
this.stateBuffer[i2] = {
yaw_: this.yaw_,
pitch_: this.pitch_,
fire: false,
jumping: this.jumping,
climbing: this.climbing,
x_: this.x_,
y_: this.y_,
z_: this.z_,
dx: this.dx,
dy: this.dy,
dz: this.dz,
controlKeys: this.controlKeys,
shots: 0,
rounds: [0, 0],
store: [0, 0]
};
}
};
Player.prototype.canJump = function() {
var canJump = this.climbing | this.onGround;
return canJump;
};
Player.prototype.jump = function() {
if (this.climbing) {
this.dy = 0.065;
this.climbing = false;
this.setJumping(true);
}
if (this.canJump()) {
this.dy = 0.13;
if (this.scope && this.scopeDelay === 0)
this.dy *= 0.66;
this.setJumping(true);
}
};
Player.prototype.setJumping = function(jumping) {
this.jumpQueued = false;
this.onGround = 0;
this.jumping = jumping;
this.stateBuffer[this.stateIdx].jumping = jumping;
};
Player.prototype.changeCharacter = function(classIdx, primaryWeaponItem, secondaryWeaponItem, shellColor, hatItem, stampItem, grenadeItem, meleeItem) {
var itemChanged = function(oldItem, newItem) {
return oldItem && !newItem || !oldItem && newItem || oldItem !== null && newItem !== null && oldItem.id !== newItem.id;
};
if (classIdx !== this.charClass || primaryWeaponItem.id !== this.primaryWeaponItem.id || secondaryWeaponItem.id !== this.secondaryWeaponItem.id || shellColor !== this.shellColor || itemChanged(this.hatItem, hatItem) || itemChanged(this.stampItem, stampItem) || this.grenadeItem !== grenadeItem || this.meleeItem !== meleeItem) {
this.charClass = classIdx;
this.primaryWeaponItem = primaryWeaponItem;
this.secondaryWeaponItem = secondaryWeaponItem;
this.shellColor = shellColor;
this.hatItem = hatItem;
this.stampItem = stampItem;
this.grenadeItem = grenadeItem;
this.meleeItem = meleeItem;
this.actor.setShellColor(shellColor);
if (this.id !== meId) {
this.actor.wearHat(this.hatItem);
this.actor.applyStamp(this.stampItem);
}
this.changeWeaponLoadout(primaryWeaponItem, secondaryWeaponItem);
}
};
Player.prototype.swapWeapon = function(idx) {
if (this.primaryWeaponDisabled) {
return false;
}
if (this.actor && this.id != meId || this.canSwapOrReload() && idx < 2) {
this.equipWeaponIdx = idx;
this.releaseTrigger();
this.swapWeaponCountdown = this.weapon.stowWeaponTime + this.weapons[idx].equipTime;
if (this.id == meId)
reticle.hide();
this.actor.wieldingMelee = false;
this.weapon.actor.stow();
if (this.id == meId) {
var out = CommOut.getBuffer();
out.packInt8(CommCode.swapWeapon);
out.packInt8(idx);
out.send(ws);
}
return true;
}
return false;
};
Player.prototype.collectItem = function(kind, applyToWeaponIdx) {
switch (kind) {
case ItemManager.AMMO:
if (this.weapons[applyToWeaponIdx].collectAmmo()) {
pAudio.play("pickup", this.actor.bodyMesh_.absolutePosition, this.id == meId);
updateAmmoUi();
return true;
}
return false;
case ItemManager.GRENADE:
if (this.grenadeCount < this.grenadeCapacity) {
this.grenadeCount++;
pAudio.play("pickup", this.actor.bodyMesh_.absolutePosition, this.id == meId);
updateAmmoUi();
return true;
}
return false;
}
};
Player.prototype.isAtReady = function() {
if (this.playing && this.weapon && this.reloadCountdown <= 0 && this.swapWeaponCountdown <= 0 && this.grenadeCountdown <= 0 && this.meleeCountdown <= 0 && (!this.actor || grenadePowerUp == false)) {
return true;
}
return false;
};
Player.prototype.canMelee = function() {
if (this.playing && this.weapon && this.recoilCountdown <= 0 && this.reloadCountdown <= 0 && this.swapWeaponCountdown <= 0 && (this.actor || this.grenadeCountdown <= 0) && this.shotsQueued <= 0) {
return true;
}
return false;
};
Player.prototype.canSwapOrReload = function() {
if (this.playing && this.weapon && this.recoilCountdown <= 0 && this.reloadCountdown <= 0 && this.swapWeaponCountdown <= 0 && this.grenadeCountdown <= 0 && this.shotsQueued <= 0 && this.meleeQueued <= 0 && (!this.actor || grenadePowerUp == false)) {
return true;
}
return false;
};
Player.prototype.fire = function() {
if (this.shield > 0) {
this.releaseTrigger();
} else if (this.isAtReady() && this.rofCountdown <= 0) {
if (this.weapon.ammo.rounds > 0) {
this.recoilCountdown = this.weapon.constructor.recoil;
this.rofCountdown = this.weapon.constructor.rof;
this.actor.fire();
this.weapon.fire();
if (this.id == meId) {
this.stateBuffer[this.stateIdx].shots++;
this.lastWeaponChange = 0;
}
if (this.weapon.constructor.automatic == false) {
this.releaseTrigger();
}
} else {
this.shotsQueued = 0;
this.weapon.actor.dryFire();
this.releaseTrigger();
}
}
};
Player.prototype.pullTrigger = function() {
if (grenadePowerUp == true && me.grenadeCountdown <= 0) {
this.cancelGrenade();
} else if (this.isAtReady() && this.rofCountdown <= 0) {
if (this.weapon.ammo.rounds > 0) {
this.triggerPulled = true;
this.fire();
} else {
if (this.weapon.ammo.store > 0) {
this.reload();
} else {
this.weapon.actor.dryFire();
}
}
return true;
}
return false;
};
Player.prototype.releaseTrigger = function() {
this.triggerPulled = false;
this.weapon.tracer = 0;
};
Player.prototype.melee = function() {
if (grenadePowerUp == true && me.grenadeCountdown <= 0) {
this.cancelGrenade();
}
if (this.shield > 0 || !this.canMelee())
return false;
this.meleeCountdown = 17;
this.recoilCountdown = 40;
if (this.id === meId) {
reticle.hide();
}
this.actor.melee();
var out = CommOut.getBuffer();
out.packInt8(CommCode.melee);
out.send(ws);
this.meleeWeapon.attack();
return true;
};
Player.prototype.reload = function() {
if (this.id != meId) {
this.weapon.actor.reload();
return;
}
if (this.weapon.ammo.rounds == this.weapon.ammo.capacity || this.weapon.ammo.store == 0 || !this.canSwapOrReload()) {
return false;
}
var rounds = Math.min(
Math.min(this.weapon.ammo.capacity, this.weapon.ammo.reload) - this.weapon.ammo.rounds,
this.weapon.ammo.store
);
this.roundsToReload = rounds;
this.scopeOut();
if (this.id === meId)
reticle.hide();
this.weapon.actor.reload();
if (this.actor.wieldingMelee)
this.actor.wieldGun();
this.releaseTrigger();
var out = CommOut.getBuffer();
out.packInt8(CommCode.reload);
out.send(ws);
if (this.weapon.ammo.rounds == 0) {
this.reloadCountdown = this.weapon.longReloadTime;
} else {
this.reloadCountdown = this.weapon.shortReloadTime;
}
return true;
};
Player.prototype.reloaded = function() {
var ammo = this.weapon.ammo;
ammo.rounds += this.roundsToReload;
ammo.store -= this.roundsToReload;
if (this.id == meId) {
reticle.show();
updateAmmoUi();
}
};
Player.prototype.cancelGrenade = function() {
grenadePowerUp = false;
me.grenadeCountdown = 30;
if (this.id == meId) {
document.getElementById("grenadeThrowContainer").style.visibility = "hidden";
}
this.actor.gripBone._frozen = false;
};
Player.prototype.throwGrenade = function() {
if (this.shield > 0)
this.disableShield();
var out = CommOut.getBuffer();
out.packInt8(CommCode.throwGrenade);
out.packFloat(Math.clamp(grenadeThrowPower, 0, 1));
out.send(ws);
me.grenadeCountdown = 80;
this.actor.reachForGrenade();
};
Player.prototype.removeFromPlay = function() {
this.playing = false;
this.controlKeys = 0;
this.jumping = false;
this.jumpQueued = 0;
this.scope = false;
this.climbing = false;
this.hardBoiledValue = 0;
this.eggBreakerValue = 0;
this.activeShellStreaks = 0;
this.pauseTargetTime = 0;
this.lastDmgType = 0;
this.meleeWeapon.collisionCountdown = 0;
this.actor.removeFromPlay();
if (this.id == meId) {
resetPlayerUI();
}
};
Player.prototype.setStats = function(state) {
let gameMode = this.gameData.private ? "Private" : "Public";
this.stats[state + gameMode]++;
let gameType2 = state + GameTypes[this.gameData.gameType].shortName;
this.stats[gameType2]++;
let damageType = state + DmgType[this.lastDmgType].name;
if (state !== "deaths") {
damageType = state + DmgType[this.lastDamageGivenType].name;
}
this.stats[damageType]++;
};
Player.prototype.resetStats = function() {
return Object.keys(this.stats).forEach((k) => {
if (k == "streak") {
return;
}
return this.stats[k] = 0;
});
};
Player.prototype.scoreKill = function() {
this.stats.kills++;
this.totalKills++;
this.stats.streak++;
this.bestGameStreak = Math.max(this.bestGameStreak, this.stats.streak);
this.bestOverallStreak = Math.max(this.bestOverallStreak, this.stats.streak);
this.setStats("kills");
this.lastDmgType = 0;
this.score = this.stats.streak;
if (this.activeShellStreaks & ShellStreak.EggBreaker) {
this.eggBreakerValue = Math.min(this.eggBreakerValue + 90, 450);
}
};
Player.prototype.kotcStatScoreCapture = function() {
this.stats.kotcCaptured++;
};
Player.prototype.kotcStatScoreWin = function() {
this.stats.kotcWins++;
};
Player.prototype.die = function() {
this.score = 0;
this.stats.streak = 0;
this.stats.deaths++;
this.totalDeaths++;
this.setStats("deaths");
this.lastDmgType = 0;
this.hp_ = 0;
this.removeFromPlay();
};
Player.prototype.beginShellStreak = function(ksType) {
this.activeShellStreaks |= ksType;
switch (ksType) {
case ShellStreak.HardBoiled:
this.hardBoiledValue = 100;
break;
case ShellStreak.EggBreaker:
this.eggBreakerValue = 450;
break;
}
this.actor.beginShellStreak(ksType);
pAudio.play("shellstreak_start", this.actor.mesh_.position, true);
};
Player.prototype.endShellStreak = function(ksType) {
this.activeShellStreaks ^= this.activeShellStreaks & ksType;
switch (ksType) {
case ShellStreak.HardBoiled:
this.hardBoiledValue = 0;
break;
}
this.actor.endShellStreak(ksType);
pAudio.play("shellstreak_end", this.actor.mesh_.position, true);
};
Player.prototype.respawn = function(x, y, z) {
this.yaw_ = Math.floor(Math.random() * Math.PI2 * 8192) / 8192;
this.pitch_ = 0;
this.x_ = x;
this.y_ = y;
this.z_ = z;
this.dx = 0;
this.dy = 0;
this.dz = 0;
this.respawnQueued = false;
this.playing = true;
this.onGround = 4;
this.climbing = false;
this.jumping = false;
this.controlKeys = 0;
this.capturing = false;
this.weapons[0].burstQueue = 0;
if (this.hp_ <= 0) {
this.hp_ = 100;
this.resetWeaponState();
} else {
this.resetWeaponState(true);
}
if (this.id == meId) {
viewingPlayerId = meId;
}
this.corrections = 0;
this.actor.resetLerp();
this.actor.restoreToPlay();
this.weapon.equip();
if (this.id == viewingPlayerId) {
shake = 0;
reticle.show();
reticle.showDot();
updateAmmoUi();
}
this.enableShield();
this.resetStateBuffer();
};
Player.prototype.resetWeaponState = function(dontReload) {
dontReload = false;
this.resetCountdowns();
this.releaseTrigger();
if (GameOptions.areAllWeaponsDisabled()) {
this.primaryWeaponDisabled = true;
this.weaponIdx = 1;
} else {
this.primaryWeaponDisabled = false;
this.weaponIdx = 0;
}
this.equipWeaponIdx = this.weaponIdx;
this.weapon = this.weapons[this.weaponIdx];
this.weapons[0].actor.gunMesh_.setEnabled(false);
this.weapons[1].actor.gunMesh_.setEnabled(false);
if (!dontReload) {
for (var i2 = 0; i2 < this.weapons.length; i2++) {
if (this.weapons[i2]) {
this.weapons[i2].ammo.rounds = this.weapons[i2].ammo.capacity;
this.weapons[i2].ammo.store = this.weapons[i2].ammo.storeMax;
}
}
this.grenadeCount = Math.max(this.grenadeCount, 1);
}
var pw = this.weapons[0];
pw.burstQueue = 0;
if (pw.constructor.burst) {
pw.ammo.rounds = Math.ceil(pw.ammo.rounds / pw.constructor.burst) * pw.constructor.burst;
pw.ammo.store = Math.ceil(pw.ammo.store / pw.constructor.burst) * pw.constructor.burst;
}
};
Player.prototype.isDead = function() {
return this.hp_ <= 0;
};
Player.prototype.resetCountdowns = function() {
this.rofCountdown = 0;
this.triggerPulled = false;
this.shotsQueued = 0;
this.meleeQueued = 0;
this.meleeCountdown = 0;
this.roundsToReload = 0;
this.recoilCountdown = 0;
this.reloadCountdown = 0;
this.reloadsQueued = 0;
this.swapWeaponCountdown = 0;
this.weaponSwapsQueued = 0;
this.grenadeCountdown = 0;
this.grenadesQueued = 0;
};
Player.prototype.selectedWeaponAllowed = function() {
if (GameOptions.areAllWeaponsDisabled()) {
return true;
} else {
return !GameOptions.value.weaponDisabled[this.charClass];
}
};
try {
fs = __require("fs");
Loader2 = void 0;
} catch (e2) {
Loader2 = window.Loader;
}
var fs;
var Loader2;
if (Loader2 === void 0) {
Loader2 = {
addTask: () => {
},
progress: () => {
},
finish: () => {
}
};
}
var Loader2;
var mapMeshes;
var duplicateWarningIssued = false;
function makeBarrier(name, scene, color) {
var barrier = BABYLON.MeshBuilder.CreateBox(name, { size: 1 }, scene);
var mat = new BABYLON.StandardMaterial();
mat.diffuseColor = color;
mat.emissiveColor = color;
mat.specularColor = BABYLON.Color3.Black();
mat.wireframe = true;
barrier.material = mat;
barrier.setEnabled(false);
return barrier;
}
function loadMapMeshes(scene, onComplete) {
mapMeshes = [null];
mapMeshes.push(makeBarrier("SPECIAL.barrier.full.verysoft", scene, BABYLON.Color3.Red()));
mapMeshes.push(makeBarrier("SPECIAL.barrier.full", scene, BABYLON.Color3.Green()));
mapMeshes.push(makeBarrier("SPECIAL.barrier.none", scene, BABYLON.Color3.White()));
var shape = [];
for (var i2 = 0; i2 <= 1; i2 += 0.125) {
var a = -Math.PI / 2 + Math.PI * i2;
var x = Math.cos(a);
var y = Math.sin(a + 0.05) * 0.5 + 0.5;
x = Math.pow(x, 1.3) * 0.25;
y = Math.pow(y, 1.3) * 0.6 - 0.48;
shape.push(new BABYLON.Vector3(x, y, 0));
}
var egg = BABYLON.MeshBuilder.CreateLathe("SPECIAL.spawn-blue.none", { shape, tessellation: 12 }, scene);
var mat = new BABYLON.StandardMaterial();
mat.diffuseColor = new BABYLON.Color3(0, 0.5, 1);
mat.specularColor = new BABYLON.Color3(0.1, 0.2, 0.4);
mat.specularPower = 8;
egg.material = mat;
egg.setEnabled(false);
mapMeshes.push(egg);
var egg = BABYLON.MeshBuilder.CreateLathe("SPECIAL.spawn-red.none", { shape, tessellation: 12 }, scene);
var mat = new BABYLON.StandardMaterial();
mat.diffuseColor = new BABYLON.Color3(1, 0.25, 0.25);
mat.specularColor = new BABYLON.Color3(0.4, 0.3, 0.3);
mat.specularPower = 8;
egg.material = mat;
egg.setEnabled(false);
mapMeshes.push(egg);
loadMeshes(scene, ["map"], function(mesh2) {
if (mesh2.parent) {
mesh2.freezeWorldMatrix();
return;
}
mapMeshes.push(mesh2);
}, function() {
for (var i3 = 1; i3 < mapMeshes.length; i3++) {
var mesh2 = mapMeshes[i3].getChildMeshes()[0];
if (mesh2) {
mapMeshes[i3].colliderMesh = mesh2;
}
}
onComplete();
});
}
function loadObjectMeshes(scene, onComplete) {
loadMeshes(
scene,
[
"egg",
"gun_eggk47",
"gun_csg1",
"gun_cluck9mm",
"gun_dozenGauge",
"gun_rpegg",
"gun_smg",
"gun_m24",
"gun_aug",
"munitions",
"muzzleFlash",
"items",
"reticle",
"melee"
],
null,
onComplete
);
}
function loadSounds(onComplete) {
BAWK.load("sound/sounds.json?" + version).then(() => onComplete());
}
function loadMaterials(scene) {
var mat;
mat = new BABYLON.StandardMaterial("bullet", scene);
mat.emissiveColor = new BABYLON.Color3(1, 1, 1);
if (shadowGen) {
var definesList = ["#define RECEIVESHADOWS"];
if (G.engineCaps.textureFloat) {
definesList.push("#define SHADOWFULLFLOAT");
}
} else {
var definesList = [];
}
definesList.push("#define MAP");
mat = new BABYLON.ShaderMaterial("map", scene, "standard", {
attributes: ["position", "normal", "color", "uv"],
uniforms: ["world", "view", "viewProjection", "vFogInfos", "vFogColor"],
defines: definesList
});
if (shadowGen) {
mat.setTexture("shadowSampler", shadowGen.getShadowMapForRendering());
mat.setMatrix("shadowLightMat", shadowGen.getTransformMatrix());
var sMap = shadowGen.getShadowMap();
if (sMap !== null) {
mat.setVector3("shadowParams", shadowGen.getDarkness(), sMap.getSize().width, shadowGen.bias);
}
}
mat.onBind = function(mesh2) {
var effect = mesh2.material.getEffect();
effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
effect.setColor3("vFogColor", scene.fogColor);
};
mat = new BABYLON.ShaderMaterial("mapNoShadow", scene, "standard", {
attributes: ["position", "normal", "color", "uv"],
uniforms: ["world", "view", "viewProjection", "vFogInfos", "vFogColor"],
defines: ["#define MAP"]
});
mat.onBind = function(mesh2) {
var effect = mesh2.material.getEffect();
var scene2 = mesh2.getScene();
effect.setFloat4("vFogInfos", scene2.fogMode, scene2.fogStart, scene2.fogEnd, scene2.fogDensity);
effect.setColor3("vFogColor", scene2.fogColor);
};
mat = new BABYLON.ShaderMaterial("standard", scene, "standard", {
attributes: ["position", "normal", "color", "uv", BABYLON.VertexBuffer.MatricesIndicesKind, BABYLON.VertexBuffer.MatricesWeightsKind],
uniforms: ["world", "view", "viewProjection", "vFogInfos", "vFogColor", "colorMult", "sunDirection", "sunColor"],
defines: ["#define COLORMULT"]
});
mat.onBind = function(mesh2) {
var effect = mesh2.material.getEffect();
var scene2 = mesh2.getScene();
effect.setFloat4("vFogInfos", scene2.fogMode, scene2.fogStart, scene2.fogEnd, scene2.fogDensity);
effect.setColor3("vFogColor", scene2.fogColor);
effect.setColor3("colorMult", mesh2.colorMult || BABYLON.Color3.White());
effect.setFloat3("sunDirection", scene2.sunLight.direction.x, scene2.sunLight.direction.y, scene2.sunLight.direction.z);
effect.setFloat3("sunColor", scene2.sunLight.diffuse.r, scene2.sunLight.diffuse.g, scene2.sunLight.diffuse.b);
if (mesh2.useBones && mesh2.computeBonesUsingShaders && mesh2.skeleton) {
var matrices = mesh2.skeleton.getTransformMatrices(mesh2);
if (matrices && effect) {
effect.setMatrices("mBones", matrices);
}
}
};
mat = new BABYLON.ShaderMaterial("standardInstanced", scene, "standard", {
attributes: ["position", "normal", "color", "uv", "world0", "world1", "world2", "world3"],
uniforms: ["world", "view", "viewProjection", "vFogInfos", "vFogColor", "sunDirection", "sunColor"],
defines: ["#define INSTANCES"]
});
mat.onBind = function(mesh2) {
var effect = mesh2.material.getEffect();
var scene2 = mesh2.getScene();
effect.setFloat4("vFogInfos", scene2.fogMode, scene2.fogStart, scene2.fogEnd, scene2.fogDensity);
effect.setColor3("vFogColor", scene2.fogColor);
effect.setFloat3("sunDirection", scene2.sunLight.direction.x, scene2.sunLight.direction.y, scene2.sunLight.direction.z);
effect.setFloat3("sunColor", scene2.sunLight.diffuse.r, scene2.sunLight.diffuse.g, scene2.sunLight.diffuse.b);
};
mat = new BABYLON.ShaderMaterial("eggShell", scene, "standard", {
attributes: ["position", "normal", "color", "uv"],
uniforms: ["world", "view", "viewProjection", "vFogInfos", "vFogColor", "hp", "cameraPosition", "outlineColor", "colorMult", "stampOffset", "sunDirection", "sunColor"],
defines: ["#define EGGSHELL"]
});
mat.onBind = function(mesh2) {
var effect = mesh2.material.getEffect();
var scene2 = mesh2.getScene();
effect.setFloat4("vFogInfos", scene2.fogMode, scene2.fogStart, scene2.fogEnd, scene2.fogDensity);
effect.setColor3("vFogColor", scene2.fogColor);
effect.setFloat("hp", mesh2.player_.hp_ / 100);
effect.setColor3("colorMult", mesh2.colorMult || BABYLON.Color3.White());
effect.setFloat3("cameraPosition", scene2.activeCamera.globalPosition.x, scene2.activeCamera.globalPosition.y, scene2.activeCamera.globalPosition.z);
effect.setColor4("outlineColor", mesh2.outlineColor, mesh2.outlineColor.a);
effect.setFloat2("stampOffset", mesh2.stampU, mesh2.stampV);
effect.setFloat3("sunDirection", scene2.sunLight.direction.x, scene2.sunLight.direction.y, scene2.sunLight.direction.z);
effect.setFloat3("sunColor", scene2.sunLight.diffuse.r, scene2.sunLight.diffuse.g, scene2.sunLight.diffuse.b);
};
mat = new BABYLON.ShaderMaterial("emissive", scene, "standard", {
attributes: ["position", "normal", "color", "uv"],
uniforms: ["world", "view", "viewProjection", "vFogInfos", "vFogColor", "emissiveColor", "sunDirection", "sunColor"],
defines: ["#define FLASH"]
});
mat.onBind = function(mesh2) {
var effect = mesh2.material.getEffect();
var scene2 = mesh2.getScene();
effect.setFloat4("vFogInfos", scene2.fogMode, scene2.fogStart, scene2.fogEnd, scene2.fogDensity);
effect.setColor3("vFogColor", scene2.fogColor);
effect.setColor3("emissiveColor", mesh2.emissiveColor || BABYLON.Color3.Black());
effect.setFloat3("sunDirection", scene2.sunLight.direction.x, scene2.sunLight.direction.y, scene2.sunLight.direction.z);
effect.setFloat3("sunColor", scene2.sunLight.diffuse.r, scene2.sunLight.diffuse.g, scene2.sunLight.diffuse.b);
};
mat = new BABYLON.ShaderMaterial("colorized", scene, "standard", {
attributes: ["position", "normal", "color", "uv"],
uniforms: ["world", "view", "viewProjection", "vFogInfos", "vFogColor", "colorMult"],
defines: ["#define COLORIZE", "#define MAP"]
});
mat.onBind = function(mesh2) {
var effect = mesh2.material.getEffect();
var scene2 = mesh2.getScene();
effect.setFloat4("vFogInfos", scene2.fogMode, scene2.fogStart, scene2.fogEnd, scene2.fogDensity);
effect.setColor3("vFogColor", scene2.fogColor);
effect.setColor3("colorMult", mesh2.colorMult || BABYLON.Color3.Black());
};
mat = new BABYLON.StandardMaterial("wireframe", scene);
mat.wireframe = true;
mat = new BABYLON.StandardMaterial("normalBackface", scene);
mat.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
mat.ambientColor = new BABYLON.Color3(0.5, 0.5, 0.5);
mat.specularColor = new BABYLON.Color3(0, 0, 0);
mat.backFaceCulling = false;
mat.twoSidedLighting = true;
mat = new BABYLON.StandardMaterial("muzzleFlash", scene);
mat.emissiveColor = BABYLON.Color3.White();
mat = new BABYLON.StandardMaterial("ui", scene);
mat.disableLighting = true;
mat.emissiveColor = BABYLON.Color3.White();
mat.fogEnabled = false;
}
function loadMeshes(scene, meshNames, onMeshLoaded, onComplete) {
var meshCount = meshNames.length;
var that = this;
var mat = scene.getMaterialByName("standard");
var numEggs = 0;
var numHands = 0;
for (var idx = 0; idx < meshCount; idx++) {
var rootUrl = "models/";
var path = meshNames[idx] + ".babylon";
if (typeof window === "undefined") {
var data2 = fs.readFileSync(path, "utf8");
data2 = data2.replace(/\r?\n|\r/g, "");
path = "data:" + data2;
rootUrl = "";
}
let id = Loader2.addTask();
BABYLON.SceneLoader.ImportMesh(
"",
rootUrl,
path,
scene,
// On success
function(meshes, partcileSystems, skeletons) {
try {
for (var m = 0; m < meshes.length; m++) {
var mesh2 = meshes[m];
if (mesh2.name == "egg") {
numEggs++;
}
if (mesh2.name == "hands") {
numHands++;
}
if (!duplicateWarningIssued && (numEggs > 1 || numHands > 1)) {
duplicateWarningIssued = true;
alert("Duplicate egg and/or hand models detected in " + path + ".\n\nOpen the weapon models in Blender and make sure egg/hands layers are turned off, then re-export.");
}
if (mesh2.setMaterial)
mesh2.setMaterial(mat);
mesh2.setEnabled(false);
mesh2.isPickable = false;
if (onMeshLoaded)
onMeshLoaded(mesh2);
}
meshCount--;
if (meshCount == 0 && onComplete) {
onComplete.call(that);
}
} catch (e2) {
console.log(e2);
}
Loader2.finish(id);
},
function(event) {
id = Loader2.progress(id, event.loaded, event.total);
}
);
}
}
var numCaptureZones;
var invalidCaptureZones = [];
function buildMapData(errorFunc) {
Collision.init();
map = { width: minMap.width, height: minMap.height + 1, depth: minMap.depth, surfaceArea: minMap.surfaceArea };
map.data = make3DArray(map.width, map.height, map.depth);
numCaptureZones = 0;
var meshIndex = {};
for (var i2 = 1; i2 < mapMeshes.length; i2++) {
var mesh2 = mapMeshes[i2];
meshIndex[mesh2.name] = i2;
}
var meshesNotFound = {};
if (typeof window === "undefined")
spawnPoints = [[], [], []];
Object.keys(minMap.data).forEach(function(meshName) {
var meshData = minMap.data[meshName];
var meshIdx = meshIndex[meshName];
var mesh3 = mapMeshes[meshIdx];
if (!meshIdx) {
meshesNotFound[meshName] = true;
} else {
var fields = meshName.split(".");
mesh3.theme = fields[0];
mesh3.shortName = fields[1];
mesh3.colliderType = fields[2];
mesh3.softness = fields[3];
if (typeof window === "undefined") {
if (mesh3.theme == "SPECIAL") {
if (mesh3.shortName.startsWith("spawn")) {
for (let cell of meshData) {
spawnPoints[0].push({ x: cell.x, y: cell.y, z: cell.z });
if (mesh3.shortName == "spawn-blue") {
spawnPoints[Team.blue].push({ x: cell.x, y: cell.y, z: cell.z });
} else {
spawnPoints[Team.red].push({ x: cell.x, y: cell.y, z: cell.z });
}
}
return;
} else if (mesh3.shortName == "spatula") {
for (let cell of meshData) {
spatulaSpawnPoints.push({ x: cell.x + 0.5, y: cell.y + 0.1, z: cell.z + 0.5 });
}
return;
}
}
}
var colliderMesh2;
var colliderPrecise;
var colliderChildren;
switch (mesh3.colliderType) {
case "full":
colliderMesh2 = Collider.fullCollisionMesh;
colliderPrecise = false;
colliderChildren = false;
break;
case "wedge":
colliderMesh2 = Collider.wedgeCollisionMesh;
colliderPrecise = true;
colliderChildren = false;
break;
case "iwedge":
colliderMesh2 = Collider.iwedgeCollisionMesh;
colliderPrecise = true;
colliderChildren = false;
break;
case "ladder":
colliderMesh2 = mesh3.colliderMesh;
colliderPrecise = false;
colliderChildren = false;
break;
case "aabb":
colliderMesh2 = mesh3.colliderMesh;
colliderPrecise = false;
colliderChildren = true;
break;
case "obb":
colliderMesh2 = mesh3.colliderMesh;
colliderPrecise = true;
colliderChildren = true;
break;
}
for (let cell of meshData) {
if (cell.ry === void 0)
cell.ry = 0;
var rx = cell.rx * Math.PI90 || 0;
var ry = cell.ry * Math.PI90 || 0;
var rz = cell.rz * Math.PI90 || 0;
map.data[cell.x][cell.y][cell.z] = {
item: void 0,
mesh: mesh3,
idx: meshIdx,
colliderMesh: colliderMesh2,
colliderPrecise,
colliderChildren,
colliderMatrix: BABYLON.Matrix.RotationYawPitchRoll(-ry, -rx, -rz),
rx,
ry,
rz
};
if (colliderMesh2) {
addColliderMesh(colliderMesh2, Collision.Type[mesh3.colliderType], cell);
}
}
if (mesh3.shortName == "capture-zone") {
for (let cellA of meshData) {
if (!map.data[cellA.x][cellA.y][cellA.z].zone) {
cellA.zone = ++numCaptureZones;
map.data[cellA.x][cellA.y][cellA.z].zone = cellA.zone;
if (cellA.y == 0) {
console.log("INVALID ZONE", cellA);
invalidCaptureZones.push(cellA.zone);
}
var hits;
do {
hits = 0;
let offsets = [
{ x: -1, z: 0 },
{ x: 1, z: 0 },
{ x: 0, z: -1 },
{ x: 0, z: 1 }
];
for (let cellB of meshData) {
if (!map.data[cellB.x][cellB.y][cellB.z].zone) {
for (let o of offsets) {
let cell = getMapCellAt(cellB.x + o.x, cellB.y, cellB.z + o.z);
if (cell && cell.zone == cellA.zone) {
hits++;
cellB.zone = cellA.zone;
map.data[cellB.x][cellB.y][cellB.z].zone = cellA.zone;
break;
}
}
}
}
} while (hits > 0);
}
}
}
}
});
var str = "";
Object.keys(meshesNotFound).forEach(function(name) {
str += name + "\n";
});
if (str != "") {
console.log("buildMapData error", str);
if (errorFunc)
errorFunc(str);
}
return meshIndex;
}
var temprot = new BABYLON.Vector3();
var temppos = new BABYLON.Vector3();
var half = new BABYLON.Vector3(0.5, 0.5, 0.5);
function addColliderMesh(mesh2, cType, cell) {
var rx = cell.rx * Math.PI90 || 0;
var ry = cell.ry * Math.PI90 || 0;
var rz = cell.rz * Math.PI90 || 0;
temppos.copyFrom(mesh2.position);
temprot.copyFrom(mesh2.rotation);
mesh2.unfreezeWorldMatrix();
mesh2.rotation.copyFromFloats(0, 0, 0);
mesh2.computeWorldMatrix();
var min = mesh2.getBoundingInfo().boundingBox.minimumWorld.clone();
var max = mesh2.getBoundingInfo().boundingBox.maximumWorld.clone();
var collider = new BABYLON.BoundingBox(min, max);
collider.matrix = BABYLON.Matrix.RotationYawPitchRoll(temprot.y, temprot.x, temprot.z);
BABYLON.Matrix.RotationYawPitchRollToRef(ry, rx, rz, Collider.matrix);
collider.matrix.multiplyToRef(Collider.matrix, collider.matrix);
collider.position = new BABYLON.Vector3(cell.x + 0.5, cell.y + 0.5, cell.z + 0.5);
collider.colliderType = cType;
collider.cell = cell;
var bb = new BABYLON.BoundingBox(
new BABYLON.Vector3(cell.x, cell.y, cell.z),
new BABYLON.Vector3(cell.x + 1, cell.y + 1, cell.z + 1)
);
collider.bb = bb;
Collision.add(collider);
mesh2.position.copyFrom(temppos);
mesh2.rotation.copyFrom(temprot);
mesh2.computeWorldMatrix();
mesh2.freezeWorldMatrix();
var children = mesh2.getChildMeshes();
for (var i2 = 0; i2 < children.length; i2++) {
addColliderMesh(children[i2], cType, cell);
}
}
function make3DArray(width, height, depth, initVal) {
var arr = Array(width);
for (var x = 0; x < width; x++) {
arr[x] = Array(height);
for (var y = 0; y < height; y++) {
arr[x][y] = Array(depth);
for (var z = 0; z < depth; z++) {
arr[x][y][z] = initVal || {};
}
}
}
return arr;
}
function getMapCellAt(x, y, z) {
if (x < 0 || x > map.width - 1 || z < 0 || z > map.depth - 1 || y < 0 || y > map.height - 1)
return null;
return map.data[x][y][z];
}
function Rocket(scene) {
this.scene = scene;
this.x = 0;
this.y = 0;
this.z = 0;
this.dx = 0;
this.dy = 0;
this.dz = 0;
this.active = false;
this.player_ = null;
this.damage = 150;
this.origin = new BABYLON.Vector3();
this.direction = new BABYLON.Vector3();
this.end = new BABYLON.Vector3();
this.dmgTypeId = "";
this.actor = new RocketActor(this);
}
Rocket.position = new BABYLON.Vector3();
Rocket.fire = function(player, pos, dir, weaponClass) {
var rocket = munitionsManager.rocketPool.retrieve();
rocket.fireThis(player, pos, dir, weaponClass);
};
Rocket.prototype.fireThis = function(player, pos, dir, weaponClass) {
this.x = pos.x;
this.y = pos.y;
this.z = pos.z;
this.origin.set(this.x, this.y, this.z);
this.direction.copyFrom(dir).normalize().scaleInPlace(weaponClass.velocity);
this.dx = this.direction.x;
this.dy = this.direction.y;
this.dz = this.direction.z;
this.radius = weaponClass.radius;
this.player_ = player;
this.weaponClass = weaponClass;
this.damage = weaponClass.damage;
this.active = true;
this.range = weaponClass.range;
this.minRange = weaponClass.minRange;
this.velocity = weaponClass.velocity;
this.dmgTypeId = weaponClass.dmgTypeId;
var res = Collider.rayCollidesWithMap(pos, dir, Collider.projectileCollidesWithCell);
if (res) {
this.end.copyFrom(res.pick.pickedPoint);
this.range = BABYLON.Vector3.Distance(pos, res.pick.pickedPoint);
}
this.actor.fire();
};
Rocket.prototype.remove = function() {
munitionsManager.rocketPool.recycle(this);
this.actor.remove();
};
Rocket.prototype.update = function() {
Rocket.position.set(this.x, this.y, this.z);
if (this.range < this.velocity) {
this.direction.scaleInPlace(this.range / this.velocity);
}
if (Collider.rayCollidesWithPlayer(Rocket.position, this.direction, this)) {
return;
}
;
this.x += this.dx;
this.y += this.dy;
this.z += this.dz;
var travel = this.velocity;
this.range -= travel;
this.minRange -= travel;
if (this.range <= 0) {
this.x -= this.dx;
this.y -= this.dy;
this.z -= this.dz;
if (this.minRange <= 0) {
this.explode();
} else {
this.poof();
}
return;
}
};
Rocket.prototype.collidesWithPlayer = function(player) {
if (this.minRange <= 0) {
this.explode();
} else {
this.poof();
}
};
Rocket.prototype.explode = function() {
this.remove();
};
Rocket.prototype.poof = function() {
Rocket.position.set(this.x, this.y, this.z);
pAudio.play("gun_rpegg_rocket_poof", Rocket.position);
var animLength = 10;
var size = 0.4;
for (var i2 = 0; i2 < 10; i2++) {
var dx = Math.random() * 0.2 - 0.1;
var dy = Math.random() * 0.2 - 0.1;
var dz = Math.random() * 0.2 - 0.1;
addExplosionSprite(explosionSmokeManager, animLength, this.x, this.y, this.z, dx, dy, dz, size, false, 0);
}
this.remove();
};
function Spatula(scene, p) {
this.scene = scene;
this.init(p);
this.lastControlTeam = 255;
this.actor = new SpatulaActor(this);
}
Spatula.prototype.init = function(p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.dy = 0;
this.controlledBy = 255;
this.controlledByTeam = 255;
};
Spatula.prototype.capture = function(player) {
if (me.id == player.id) {
var el = document.getElementById("spatulaPlayer");
el.className = "capture";
}
if (player.team != this.lastControlTeam) {
metaGame.teamScore[player.team] = 0;
}
this.controlledBy = player.id;
this.controlledByTeam = player.team;
this.lastControlTeam = player.team;
BAWK.play("capture_spatula");
var el = document.getElementById("teamScoreNum" + player.team);
el.innerText = metaGame.teamScore[player.team];
};
Spatula.prototype.drop = function() {
var player = players[this.controlledBy];
this.controlledBy = 255;
this.controlledByTeam = 255;
this.x = player.x_;
this.y = player.y_;
this.z = player.z_;
this.dy = player.dy + 0.05;
var el = document.getElementById("spatulaPlayer");
el.className = "drop";
this.actor.drop();
};
Spatula.prototype.respawn = function() {
var n = spatulaSpawnPoints.length;
var p = spatulaSpawnPoints[Math.randomInt(0, n)];
this.init(p);
let out = CommOut.getBuffer();
metaGame.packState(out);
sendToAll(out);
};
Spatula.prototype.update = function() {
if (this.controlledBy == 255) {
var pdy = this.dy;
this.dy -= GameOptions.value.gravity * 0.012;
var ndy = 0.5 * (this.dy + pdy);
var oldY = this.y;
this.y += ndy;
if (this.collidesWithMap()) {
this.y = oldY;
this.dy *= -0.5;
}
} else {
var player = players[this.controlledBy];
if (player) {
this.x = player.x_ - Math.sin(player.yaw_) * 0.3;
this.y = player.y_;
this.z = player.z_ - Math.cos(player.yaw_) * 0.3;
}
}
};
Spatula.v1 = new BABYLON.Vector3();
Spatula.prototype.collidesWithMap = function() {
Spatula.v1.set(this.x, this.y, this.z);
return Collider.meshCollidesWithMap(Collider.playerCollisionMesh, Spatula.v1);
};
function isBadWord(word) {
word = " " + word + " ";
var str = word.toLowerCase().replace(/[^a-zA-Z0-9|!\|@|$|;|¡]/g, "").replace(/6|g/g, "9").replace(/b/g, "6").replace(/\||l|i|1|;|¡/g, "!").replace(/e/g, "3").replace(/a|@/g, "4").replace(/o/g, "0").replace(/s|\$/g, "5").replace(/t/g, "7").replace(/z/g, "2").replace(/7h3|my|y0ur|7h3!r|h!5|h3r/g, "");
var i1 = str.search(/( 94y | 455 )/);
str = str.replace(/ /g, "");
var reg = /(n421|5chu72574ff3!|n994|m457ur647|m4r!c4|n!qq4|fck|cn7|57urm4673!!un9|!uf7w4ff3|k!4n|66c|n993r|n!443r|n!99r|m4y473|64ch!ch4|64ch!ch3|c474!uf0|fr4nchu7|fr!j0!3r0|9464ch0|94chup!n|m0r0m!3rd4|54!74mur05|pu74|j0d3r|m0n90|c0n0|c4r4j0|m!3rd4|20rr4|chup4m3!|cu!0|p3nd3j0|c46r0n|0r70|pu70|p!r06|qu33f|455h47|ch04d|cum|k0ck|k0ch|pu74|n!94|n3993r|4fr!c4n|kn336r0|5ch00!5h007|n!qq3r|73rr0r!5t|qu33r|d!ck|w4nk|p!55|7357!c|735735|64!!5|nu75|nu72|j3w|k!k3|r374r|4u7!5|d0wn55|6006|8d|p0rn|5w4!!0w|347m3|347my|d!k|0r4!|5p0093|fuk|j!2|5u!c!d|m4573r6|5p0063|5p3rm|p3nu5|pu55y|6u7753x|fux|6u77h0!3|4n4!|4nu5|k!!!b!4ck5|murd3rb!4ck5|h!7!3r|w3764ck|49!n4|94y|455h0!3|5uck|j3w|5p!c|ch!nk|n!994|n!993|n!663|n!994|n!664|5h!7|6!7ch|fuck|cun7|kkk|wh0r3|f49|7w47|p3n!|r4p3w0m|r4p39!r|r4p!57|r4p3r|r4p3|r4p!n|n!93r|!d!07|c0ck|dum6|5!4v3|7!75|@|455|pu5y|ju!cy|nud3|fk|v!49r4|64n9|53x|h03|d473|h473|d47!n9|d473r|h4ck|h4ck3r|h4ck!n9|60yfr!3nd|9!r!fr!3nd|900k|gf|bf|m0nk3y|m0nk!35|d4ddy|5!u7|pr057!7u7|nud3|33m4!!|d!ckh34d|r374rd|n4993r|n0993r|4d0!f|kn339r0w|6umh0!3|c0kk|cuck|!3573r|!5r43!|p4!357!n3|ph!!3|n3994|f4ck|pr3d470r|pn!5|n!95|fr!ck|m0!3573r|n!94rd!y|m0!357|73rr0r!57|5h!4d|60!!0ck5|7r4n5|64!!649|n!9993r|ky5|60yfr!3nd|9!r!fr!3nd|d0uch3|pu55!35|57473f4rm)/g;
var i2 = str.search(reg);
str = str.replace(/(.)(?=\1)/g, "");
var i3 = str.search(reg);
return i1 > -1 || i2 > -1 || i3 > -1;
}
var sessionStats = class {
constructor() {
this.kills = 0;
this.deaths = 0;
this.suicides = 0;
this.streak = 0;
this.weapons = {};
this.sessionStart = 0;
this.sessionEnd = 0;
this.endTime = 0;
this.playTime = 0;
this.ratio = 0;
this.charClass = {};
this.init();
}
init() {
this.setupWeapons();
this.start();
}
start() {
this.sessionStart = Date.now();
}
end() {
this.endTime = this.getPlayTimeInGame();
this.getPlayTime();
}
setupWeapons() {
DmgType.forEach((el) => this.weapons[el.name] = { deaths: 0, kills: 0 });
Object.keys(CharClass).forEach((key) => this.charClass[key] = JSON.parse(JSON.stringify(this.weapons)));
Object.keys(this.charClass).forEach((key) => {
this.charClass[key].kills = 0;
this.charClass[key].deaths = 0;
});
console.log(this.charClass);
}
getRatio() {
this.ratio = Math.floor(this.kills / Math.max(this.kills + this.deaths, 1) * 100);
}
getPlayTime() {
this.sessionEnd = Date.now() - this.sessionStart;
const seconds = (this.sessionEnd % 6e4 / 1e3).toFixed(0);
this.playTime = Math.floor(this.sessionEnd / 6e4) + ":" + (seconds < 10 ? "0" : "") + seconds;
}
getPlayTimeInGame() {
if (!this.sessionStart) {
return "0:00";
}
const sessionEnd = Date.now() - this.sessionStart;
const seconds = (sessionEnd % 6e4 / 1e3).toFixed(0);
return Math.floor(sessionEnd / 6e4) + ":" + (seconds < 10 ? "0" : "") + seconds;
}
updateTerminus(classType, dmgType, endingType, isSuicide) {
this.charClass[classType][dmgType][endingType]++;
this.charClass[classType][endingType]++;
this.weapons[dmgType][endingType]++;
this[endingType]++;
if (isSuicide)
this.suicides++;
}
getStats() {
return {
kills: this.kills,
deaths: this.deaths,
suicides: this.suicides,
weapons: this.weapons,
charClass: this.charClass,
playTime: this.getPlayTimeInGame(),
endTime: this.endTime,
ratio: this.ratio
};
}
set kills(val) {
this._kills = val;
this.getRatio();
}
get kills() {
return this._kills;
}
set deaths(val) {
this._deaths = val;
this.getRatio();
}
get deaths() {
return this._deaths;
}
};
var CHICKNWINNERLOG = (message, msg2) => {
console.log(
"%c%s",
`color: white; background: #006700; padding: 2px 6px; border-radius: 3px; margin-right: 5px;`,
`Chick'n Winner`,
message,
msg2 ? msg2 : ""
);
};
function chwTryPlay() {
if (chicknWinner.count <= CHICKWINNER.dailyLimit && chicknWinner.ready) {
AIPVideoAds.isChwRequest = true;
vueApp.chicknWinnerError(false);
if (chicknWinner.count === 0) {
CHICKNWINNERLOG("chwTryPlay() First play!");
getIncetivizedReward();
} else {
checkUpgrade(() => {
if (G.playerAccount.isUpgraded()) {
CHICKNWINNERLOG("chwTryPlay() VIP. No ads for you! Thank you!");
getIncetivizedReward();
} else {
CHICKNWINNERLOG("chwTryPlay() No vip. Subscribe today for no video ads!");
AIPVideoAds.play("shellshock.io_rpreroll_30s");
}
}, (err) => {
AIPVideoAds.isChwRequest = false;
chwErrors("chwTryPlay()", err);
});
}
} else {
CHICKNWINNERLOG("checkStartChicknWinner not ready");
checkStartChicknWinner();
}
}
function checkStartChicknWinner() {
let end = Math.trunc(Date.now() / 1e3) + 1;
let span = CHICKWINNER.dailyLimit;
let count = 0;
chicknWinner = new Chw(end, span, count);
CHICKNWINNERLOG("checkStartChicknWinner() start");
api_chicknWinnerPlayerRewardCheck((results) => {
CHICKNWINNERLOG("checkStartChicknWinner() success");
const Limiter = results.limitData;
console.log("api_chicknWinnerPlayerRewardCheck data", results.limitData);
const now2 = Math.trunc(Date.now() / 1e3);
vueApp.chicknWinnerError(false);
if (Object.keys(Limiter).length > 0) {
count = Limiter.limit;
if (Limiter.limit <= CHICKWINNER.dailyLimit) {
if (Limiter.hasOwnProperty("span")) {
end = now2 + Limiter.span;
} else {
end = now2 + 1;
}
span = CHICKWINNER.cooldown;
} else {
end = now2 + Limiter.period;
span = CHICKWINNER.dailyCooldown;
}
} else {
end = now2 + 1;
span = CHICKWINNER.cooldown;
}
chicknWinner = new Chw(end, span, count);
}, (data2) => chwErrors("checkStartChicknWinner()", data2.error));
}
function getIncetivizedReward() {
if (AIPVideoAds.isChwRequest) {
api_incentivizedVideoRewardRequest((response) => {
AIPVideoAds.isChwRequest = false;
const result = response.result;
CHICKNWINNERLOG(`getIncetivizedReward() response ${result}`);
if (result !== "SUCCESS") {
if (result === "SESSION_EXPIRED") {
chwErrors("getIncetivizedReward", result);
}
return;
}
const count = chicknWinner.count ? chicknWinner.count : "free";
if (response.reward.itemIds.length > 0) {
const Item = G.catalog.findItemById(response.reward.itemIds[0]);
G.playerAccount.addToInventory(Item, true);
if (Item) {
ga("send", "event", "Chickn Winner", "Reward", `${count} - item`);
if (response.reward_lvl || response.reward.rewardTier) {
ga("send", "event", "Chickn Winner", "Reward item", `${Item.name} - ${response.reward.rewardTier ? response.reward.rewardTier : response.reward_lvl}`);
}
}
}
if (response.reward.eggsGiven && response.reward.eggsGiven > 0) {
ga("send", "event", "Chickn Winner", "Reward", `${count} - ${response.reward.eggsGiven}`);
ga("send", "event", "Chickn Winner", "Reward amount", `${response.reward.eggsGiven}`);
}
vueApp.chw.reward.ownedItem = response.ownedItemId;
vueApp.chw.reward.eggs = response.reward.eggsGiven;
response.reward.itemIds.forEach((id) => vueApp.chw.reward.itemIds.push(id));
vueApp.chicknWinnerError(false);
vueApp.showChicknWinnerPopup();
}, (response) => chwErrors("getIncetivizedReward", response.error));
} else {
CHICKNWINNERLOG("getIncetivizedReward() Request called directly. CHW not played");
}
}
function chwErrors(fnName, error) {
vueApp.chicknWinnerError(true);
vueApp.chwOnClick(false);
if (!hasValue(error)) {
return;
}
if (error === "SESSION_EXPIRED") {
vueApp.showGenericPopup("session_expired", "session_expired_msg", "ok");
} else {
vueApp.showGenericPopup("uh_oh", "purchase_disabled", "ok");
}
if (fnName)
console.log(`${fnName} fail: `, error);
}
var meleeSwung;
var InputQueue = class _InputQueue {
static init() {
_InputQueue.inputs = [0, 0, 0, 0, 0];
meleeSwung = false;
}
static add(controlId) {
_InputQueue.inputs[controlId] = Date.now();
}
static update() {
for (var i2 = 0; i2 < _InputQueue.inputs.length; i2++) {
var inputTime = _InputQueue.inputs[i2];
if (Date.now() - inputTime < 100) {
switch (i2) {
case _InputQueue.jump:
break;
case _InputQueue.fire:
if (me.pullTrigger()) {
_InputQueue.remove(i2);
}
break;
case _InputQueue.swap:
if (me.swapWeapon(me.weaponIdx == 0 ? 1 : 0))
_InputQueue.remove(i2);
break;
case _InputQueue.reload:
if (me.reload())
_InputQueue.remove(i2);
break;
case _InputQueue.melee:
if (me.melee()) {
if (!meleeSwung) {
ga("send", "event", "weapon", "triggered", "Melee");
meleeSwung = true;
}
_InputQueue.remove(i2);
}
;
break;
}
}
}
if (me.triggerPulled && !(controlKeys & CONTROL.fire)) {
me.releaseTrigger();
}
}
static remove(controlId) {
_InputQueue.inputs[controlId] = 0;
}
};
InputQueue.jump = 0;
InputQueue.fire = 1;
InputQueue.swap = 2;
InputQueue.reload = 3;
InputQueue.melee = 4;
if (parsedUrl.query.adTest) {
adTest = true;
}
var VideoAds = class {
constructor() {
this.rewardedAdPlayed = false;
this.didVideoPlay = false;
this.adsBlocked = false;
this.isPlayingVideoAd = false;
this.callback = null;
this.adUnit = null;
this.isChwRequest = false;
this.cgAdType = "midgame";
this.cgErr = false;
this.cgErrTxt = "CG video ad";
}
init() {
if (pokiActive || crazyGamesActive || G.productBlockAds) {
this.adInPlayActive = false;
console.log("initAdInPlay Cancelled. Is portal?", pokiActive || crazyGamesActive);
return;
}
let outer = this;
try {
outer.ADSLOG("F79520", "Shell Shockers AIP", "AIP init success!");
outer.adInPlayActive = !testCrazy ? true : false;
aiptag.cmd.player.push(function() {
aipPrerollPlayer = new aipPlayer({
AD_WIDTH: 960,
AD_HEIGHT: 540,
AD_FULLSCREEN: false,
AD_CENTERPLAYER: true,
LOADING_TEXT: "loading advertisement",
PREROLL_ELEM: function() {
return document.getElementById("preroll");
},
AIP_COMPLETE: function(state) {
outer.ADSLOG("F79520", "Shell Shockers AIP_COMPLETE", state);
outer.afterVideoAdComplete(state);
ga("send", "event", "aip-complete", "regular", state);
},
AIP_REMOVE: function() {
},
AIP_REWARDEDCOMPLETE: function(state) {
outer.ADSLOG("F79520", "Shell Shockers AIP Reward Complete", state);
outer.afterVideoAdComplete(state);
ga("send", "event", "aip-complete", "reward", state);
},
AIP_REWARDEDGRANTED: function(state) {
outer.ADSLOG("F79520", "Shell Shockers AIP Reward Granted", state);
outer.rewardedAdPlayed = true;
ga("send", "event", "aip-complete", "reward-granted", state);
}
});
outer.checkAdBlocker();
});
} catch (e2) {
outer.ADSLOG("F79520", "Shell Shockers AIP", `AIP error message: ${e2}`);
outer.error();
}
}
set adBlocker(value) {
this.adsBlocked = value;
if (this.adsBlocked && !G.productBlockAds) {
this.adBlockerDetected();
}
}
get adBlocker() {
return this.adsBlocked;
}
checkAdBlocker() {
this.adBlocker = aipAPItag && aipAPItag.hasOwnProperty("sdkBlocked") && aipAPItag.sdkBlocked;
}
adBlockerDetected() {
vueApp.chwAdBlockerDetected();
this.adInPlayActive = false;
}
play(adUnit, callback) {
this.adUnit = adUnit;
this.callback = callback;
if (adTest) {
this.ADSLOG("F79520", "Shell Shockers AIP", "AD test active");
}
if (testCrazy) {
this.ADSLOG("3C1E6E", "CG video ad", "Crazy Games test ads");
}
this.ADSLOG("F79520", "Shell Shockers AIP", `Play video ads Ad unit: ${this.adUnit}`);
if (!this.isChwRequest)
this.setAdVideoLocalStorage();
if (crazyGamesActive) {
this.ADSLOG("3C1E6E", this.cgErrTxt, "Crazy Game video ad request.");
if (this.isChwRequest) {
this.cgAdType = "rewarded";
}
this.cgAdRequested();
return;
}
vueApp.setDarkOverlay(true, vueApp.ui.overlayClass.inGame);
setVolume(0);
this.isPlayingVideoAd = true;
this.preroll();
}
preroll() {
if (this.adBlocker) {
this.ADSLOG("F79520", "Shell Shockers AIP", `Ad blocker detected.`);
this.showAdBlockerVideo();
} else {
let outer = this;
if (typeof aipPrerollPlayer !== "undefined") {
if (aiptag.cmd.display.hasOwnProperty("push") && aiptag.cmd.player.hasOwnProperty("push")) {
aiptag.cmd.player.push(function() {
try {
outer.ADSLOG("F79520", "Shell Shockers AIP", `Play: ${outer.adUnit}`);
vueApp.gameUiAddClassForNoScroll();
if (inGame) {
vueApp.hideGameMenu();
vueApp.setDarkOverlay(true, vueApp.ui.overlayClass.inGame);
}
aipPrerollPlayer.startPreRoll(outer.adUnit);
} catch (e2) {
outer.error(e2);
vueApp.setDarkOverlay(false);
this.onVideoAdCompleted("F79520", "preroll error");
}
});
} else {
outer.error("push method missing");
vueApp.setDarkOverlay(false);
this.onVideoAdCompleted("F79520", "preroll error");
}
} else {
outer.error("aipPrerollPlayer undefined");
vueApp.setDarkOverlay(false);
this.onVideoAdCompleted("F79520", "preroll error");
}
}
}
afterVideoAdComplete(err) {
this.ADSLOG("F79520", "Shell Shockers AIP", "afterVideoAdComplete");
if (!this.isChwRequest) {
vueApp.setDarkOverlay(false);
}
if (err && !["video-ad-skipped", "video-ad-completed"].includes(err)) {
this.error(err);
} else {
this.didVideoPlay = true;
}
this.onVideoAdCompleted("F79520", "Shell Shockers AIP");
}
onVideoAdCompleted(color, title) {
this.ADSLOG(color, title, `is getting chickn winner: ${this.isChwRequest}`);
if (this.isChwRequest) {
if (this.didVideoPlay) {
getIncetivizedReward();
} else {
this.isChwRequest = false;
vueApp.showGenericPopup("ad_blocker_nugget_title", "ad_blocker_nugget_content", "ok");
}
} else {
if (inGame) {
vueApp.disableRespawnButton(false);
vueApp.showGameMenu();
}
vueApp.gameUiRemoveClassForNoScroll();
}
setVolume();
this.didVideoPlay = false;
this.rewardedAdPlayed = false;
if (this.callback) {
this.callback();
this.callback = null;
}
this.adUnit = null;
}
error(afterPlayErr) {
if (afterPlayErr) {
this.ADSLOG("F79520", "Shell Shockers AIP video error: ", afterPlayErr);
}
const wasCHW = this.isChwRequest;
const wasPlayingVideoAd = this.isPlayingVideoAd;
if (afterPlayErr === "user-has-adblock") {
this.adBlockerDetected();
}
vueApp.chwOnClick(false);
this.didVideoPlay = false;
this.isChwRequest = false;
this.isPlayingVideoAd = false;
if (wasPlayingVideoAd && wasCHW) {
checkUpgrade(() => {
if (!G.playerAccount.isUpgraded()) {
if (wasCHW) {
vueApp.showGenericPopup("chw_video_error_title", "chw_video_error_msg", "ok");
checkStartChicknWinner();
}
}
});
}
}
isAdBlocking() {
if (crazyGamesActive) {
return crazysdk.hasAdblock;
} else {
return this.adBlocker;
}
}
showAdBlockerVideo() {
vueApp.showAdBlockerVideo();
setTimeout(() => {
vueApp.hideAdBlockerVideo();
vueApp.gameUiRemoveClassForNoScroll();
if (crazyGamesActive || testCrazy) {
this.onVideoAdCompleted();
} else {
this.afterVideoAdComplete();
}
}, adBlockerVideoTimer);
}
ADSLOG(color, title, message) {
console.log(
"%c%s",
`color: white; background: #${color}; padding: 2px 6px; border-radius: 3px; margin-right: 5px;`,
title,
message
);
}
setAdVideoLocalStorage() {
localStore.setItem("lastPreRoll", Date.now());
}
cgAdRequested() {
this.ADSLOG("3C1E6E", this.cgErrTxt, "requested.");
if (crazysdk.hasAdblock) {
this.showAdBlockerVideo();
setTimeout(() => this.cgRequestAd(), adBlockerVideoTimer);
return;
} else {
this.cgRequestAd();
}
}
cgRequestAd() {
this.cgListeners();
crazysdk.requestAd(this.cgAdType);
this.cgAdType = "midgame";
}
cgListeners() {
this.ADSLOG("3C1E6E", this.cgErrTxt, "add eventListeners");
this.cgAdStarted = this.cgAdStarted.bind(this);
this.cgAdError = this.cgAdError.bind(this);
this.cgAdFinished = this.cgAdFinished.bind(this);
crazysdk.addEventListener("adStarted", this.cgAdStarted);
crazysdk.addEventListener("adError", this.cgAdError);
crazysdk.addEventListener("adFinished", this.cgAdFinished);
}
cgRmListeners() {
this.ADSLOG("3C1E6E", this.cgErrTxt, "remove eventListeners");
vueApp.setDarkOverlay(false);
crazysdk.removeEventListener("adStarted", this.cgAdStarted);
crazysdk.removeEventListener("adError", this.cgAdError);
crazysdk.removeEventListener("adFinished", this.cgAdFinished);
}
cgAdStarted(e2) {
this.ADSLOG("3C1E6E", this.cgErrTxt, "started.", e2);
if (inGame)
vueApp.hideGameMenu();
vueApp.setDarkOverlay(true, vueApp.ui.overlayClass.inGame);
this.isPlayingVideoAd = true;
this.didVideoPlay = true;
setVolume(0);
}
cgAdFinished(e2) {
this.ADSLOG("3C1E6E", this.cgErrTxt, "ended.", e2);
vueApp.setDarkOverlay(false);
if (this.cgErr) {
this.didVideoPlay = false;
this.rewardedAdPlayed = false;
}
this.onVideoAdCompleted("3C1E6E", this.cgErrTxt);
this.cgRmListeners();
this.cgErr = false;
if (crazysdk.hasAdblock) {
vueApp.hideAdBlockerVideo();
}
}
cgAdError(e2) {
this.ADSLOG("3C1E6E", this.cgErrTxt, "error.", e2);
this.cgErr = true;
this.didVideoPlay = false;
this.cgAdFinished();
}
};
if (adTagDebug) {
console.log("adTagDebug debug is on");
}
function callApi(apiRequest, successCallback2, errorCallback2, closeCallback) {
console.log("'{0}' api command".format(apiRequest.cmd));
try {
console.log("services server: " + G.servicesServer);
var servicesWs = new WebSocket(G.servicesServer);
} catch (e2) {
console.log(e2);
}
servicesWs.onopen = function(e2) {
servicesWs.send(JSON.stringify(apiRequest));
console.log("servicesWs opened, and " + apiRequest.cmd + " request sent");
};
servicesWs.onmessage = function(e2) {
var response = null;
try {
response = JSON.parse(e2.data);
} catch (e3) {
console.log("Invalid data returned from services API", e3.data);
errorCallback2(e3);
return;
}
if (response.error) {
console.log(apiRequest.cmd + " error: " + JSON.stringify(response.error));
errorCallback2(response);
} else {
successCallback2(response);
}
servicesWs.close();
};
servicesWs.onclose = function(e2) {
console.log(apiRequest.cmd + " servicesWs closed, code: " + e2.code, "reason: " + e2.reason, "clean: " + e2.wasClean);
if (closeCallback) {
closeCallback(e2.code);
}
};
servicesWs.onerror = function(e2) {
console.log(apiRequest.cmd + " servicesWs error: " + JSON.stringify(e2));
Loader2.hide();
errorCallback2(e2);
};
}
function api_auth(firebaseToken, successCallback2, errorCallback2, closeCallback) {
var authRequest = {
cmd: "auth",
firebaseToken
};
callApi(authRequest, successCallback2, errorCallback2, closeCallback);
}
function api_checkBalance() {
var balanceRequest = {
cmd: "checkBalance",
firebaseId: G.playerAccount.firebaseId
};
var onResponse = function(balanceResponse) {
console.log("Check Balance response: " + JSON.stringify(balanceResponse));
if (!balanceResponse.error) {
G.playerAccount.setEggBalances(balanceResponse.currentBalance);
} else {
console.log("Check Balance call failed: " + JSON.stringify(balanceResponse.error));
}
};
var onError = function() {
console.log("Error running check balance call");
};
callApi(balanceRequest, onResponse, onError);
}
function api_buy(item, successCallback2, failureCallback) {
var buyRequest = {
cmd: "buy",
firebaseId: G.playerAccount.firebaseId,
itemId: item.id,
save: typeof checkStatus !== "undefined" ? checkStatus() : true
};
var onResponse = function(purchaseResult) {
console.log("purchase response: " + purchaseResult.result);
switch (purchaseResult.result) {
case "SUCCESS":
if (hasValue(purchaseResult.itemId)) {
var boughtItem = G.catalog.findItemById(purchaseResult.itemId);
G.playerAccount.addToInventory(boughtItem, true);
}
G.playerAccount.currentBalance = purchaseResult.currentBalance;
vueApp.statsLoading();
updateStats();
pokiHappyTime(0.5);
successCallback2();
break;
case "INSUFFICIENT_FUNDS":
vueApp.needMoreEggsPopupCall();
break;
case "ALREADY_OWNED":
vueApp.showGenericPopup("p_buy_owned_title", "p_buy_owned_content", "ok");
break;
case "ERROR_CODE_4225":
vueApp.showGenericPopup("p_error_4225_title", "p_buy_error_content", "ok");
break;
case "PLAYER_NOT_FOUND":
case "ITEM_NOT_FOUND":
case "ERROR":
default:
failureCallback();
break;
}
};
var onError = function() {
failureCallback();
};
callApi(buyRequest, onResponse, onError);
}
function api_redeem(code, successCallback2, failureCallback) {
if (code == shloopyBloopers) {
vueApp.giveStuffPopup.eggOrg = true;
vueApp.showGiveStuffPopup("p_give_stuff_title");
return;
}
var redeemRequest = {
cmd: "redeem",
firebaseId: G.playerAccount.firebaseId,
id: G.playerAccount.id,
code
};
var onResponse = function(redeemResult) {
console.log("Redeem Code response: " + redeemResult.result);
switch (redeemResult.result) {
case "SUCCESS":
if (!redeemResult.eggs_given) {
redeemResult.eggs_given = 0;
}
if (!redeemResult.item_ids) {
redeemResult.item_ids = [];
}
if (redeemResult.eggs_given && redeemResult.eggs_given > 0) {
api_checkBalance();
}
var itemsGiven = [];
if (redeemResult.item_ids) {
for (var i2 = 0; i2 < redeemResult.item_ids.length; i2++) {
var redeemedItem = G.catalog.findItemById(redeemResult.item_ids[i2]);
G.playerAccount.addToInventory(redeemedItem);
itemsGiven.push(redeemedItem);
}
}
pokiHappyTime(0.5);
successCallback2(redeemResult.eggs_given, itemsGiven);
break;
case "PLAYER_NOT_FOUND":
vueApp.showGenericPopup("p_redeem_error_no_player_title", "p_redeem_error_no_player_content", "ok");
break;
case "CODE_DOUBLE_DOUBLE":
vueApp.showGenericPopup("p_redeem_code_redeem_in_progress_title", "p_redeem_code_redeem_in_progress_content", "ok");
break;
case "CODE_PREV_REDEEMED":
vueApp.showGenericPopup("p_redeem_prev_title", "p_redeem_prev_content", "ok");
break;
case "CODE_NOT_FOUND":
vueApp.showGenericPopup("p_redeem_badcode_title", "p_redeem_badcode_content", "ok");
break;
case "RATE_LIMIT_REACHED":
vueApp.showGenericPopup("p_redeem_ratelimited_title", "p_redeem_ratelimited_content", "ok");
break;
case "ERROR":
default:
failureCallback();
break;
}
};
var onError = function() {
console.log("there be an error");
failureCallback();
};
callApi(redeemRequest, onResponse, onError);
}
function api_saveLoadout(loadout, callback) {
var saveLoadoutRequest = {
cmd: "saveLoadout",
firebaseId: G.playerAccount.firebaseId,
save: typeof checkStatus !== "undefined" ? checkStatus() : true,
loadout
};
var timeout2;
if (callback) {
timeout2 = setTimeout(() => {
callback();
}, 5e3);
}
var onResponse = function(saveLoadoutResponse) {
console.log("Save Loadout response: " + JSON.stringify(saveLoadoutResponse));
if (!saveLoadoutResponse.error) {
console.log("Successfully saved player loadout");
} else {
console.log("Save Loadout call failed: " + JSON.stringify(saveLoadoutResponse.error));
}
if (callback) {
clearTimeout(timeout2);
callback();
}
};
var onError = function() {
console.log("Error running save loadout call");
};
callApi(saveLoadoutRequest, onResponse, onError);
}
G.api_saveLoadout = api_saveLoadout;
function api_xsollaToken(productSku, successCallback2, errorCallback2, isSubscription, playerSource) {
isSubscription = isSubscription ? isSubscription : false;
var getXsollaTokenRequest = {
cmd: "xsollaToken",
firebaseId: G.playerAccount.firebaseId,
productSku,
subscription: isSubscription,
playerSource
};
callApi(getXsollaTokenRequest, successCallback2, errorCallback2);
}
function api_feedback(feedbackType, email, feedback) {
const feedbackError = () => vueApp.showGenericPopup("uh_oh", "feedback_error_msg", "ok");
var glInfo = G.engine.getGlInfo();
var caps = G.engine.getCaps();
var pickedWeaponIds = [];
for (var c = 0; c < CharClass.length; c++) {
pickedWeaponIds.push([
G.playerAccount.pickedWeapons[c][0].id,
G.playerAccount.pickedWeapons[c][1].id
]);
}
var debugJSON = "";
if (feedbackType === FeedbackType.deleteAccount && !hasValue(G.playerAccount.firebaseId)) {
feedbackError();
return;
}
try {
debugJSON = JSON.stringify({ debugObject, debugArray });
} catch (e2) {
console.log(e2);
}
var feedbackRequest = {
cmd: "feedback",
feedbackType,
gameVersion: version,
userAgent: window.navigator.userAgent,
username: vueApp.playerName,
comments: feedback,
email,
firebaseId: G.playerAccount.firebaseId || null,
fromEU: isFromEU,
gameServer: vueApp.loc[vueApp.currentRegionLocKey] || null,
session: G.playerAccount.session || null,
ping: pingSamples > 0 ? Math.floor(pingTotal / pingSamples) : null,
highestPing: highestPing || null,
fps: fpsSamples > 0 ? Math.ceil(fpsTotal / fpsSamples) : null,
gameType: gameType || null,
privateGame: privateGame || null,
localKills: kills || 0,
localDeaths: deaths || 0,
localStreak: bestOverallStreak || 0,
url: parsedUrl.root,
referrer: document.referrer,
gameCode: gameCode || null,
screenSize: screen.width + "x" + screen.height,
colorDepth: screen.colorDepth,
pixelDepth: screen.pixelDepth,
innerSize: window.innerWidth + "x" + window.innerHeight,
glVendor: glInfo.vendor,
renderer: glInfo.renderer,
glVersion: glInfo.version,
maxTextureSize: caps.maxTextureSize,
fov: camera ? camera.fov : null,
controls: localStorage.getItem("controls"),
ofAge: consent ? consent.ofAge : null,
targetedAds: consent ? consent.targetedAds : null,
volume: settings.volume,
mouseSpeed: settings.mouseSpeed,
mouseInvert: settings.mouseInvert,
holdToAim: settings.holdToAim,
enableChat: settings.enableChat,
safeNames: settings.safeNames,
autoDetail: settings.autoDetail,
shadowsEnabled: settings.shadowsEnabled,
highRes: settings.highRes,
selectedClass: G.playerAccount.classIdx,
selectedColor: G.playerAccount.colorIdx,
hat: G.playerAccount.hatItem ? G.playerAccount.hatItem.id : null,
stamp: G.playerAccount.stampItem ? G.playerAccount.stampItem.id : null,
grenade: G.playerAccount.grenadeItem ? G.playerAccount.grenadeItem.id : null,
weapons: "[[0,0],[0,0],[0,0]]",
// Need to widen the column for this: JSON.stringify(pickedWeaponIds),
timesPlayed: null,
// personal.timesPlayed,
xsollaToken: null,
current_balance: G.playerAccount.currentBalance,
log: console.logArray(),
debug: debugJSON
};
callApi(feedbackRequest, success, fail);
function success(res) {
const message = { title: "", desc: "" };
if (res.status) {
if (res.type === FeedbackType.deleteAccount) {
message.title = "feedback_delete_title";
message.desc = "feedback_delete_msg";
} else {
message.title = "feedback_sent_title";
message.desc = "feedback_sent_msg";
}
} else {
message.title = "uh_oh";
message.desc = "feedback_error_msg";
}
setTimeout(function() {
vueApp.showGenericPopup(message.title, message.desc, "ok");
}, 1e3);
}
function fail(err) {
feedbackError();
}
}
function checkUpgrade(success, error) {
var successCallback2 = function(response) {
G.playerAccount.setUpgrade(response);
if (!G.playerAccount.isUpgraded() && inGame) {
document.getElementById("chickenBadge").style.display = "none";
}
G.productBlockAds = G.playerAccount.isUpgraded();
if (G.productBlockAds)
vueApp.runProductCheck();
if (success)
success(response);
};
var errorCallback2 = function(response) {
if (error)
error(response);
console.log("Error checking account upgrade status");
};
api_checkUpgrade(successCallback2, errorCallback2);
}
G.checkUpgrade = checkUpgrade;
function api_checkUpgrade(successCallback2, errorCallback2) {
var upgradeCheckRequest = {
cmd: "checkUpgrade",
firebase_id: G.playerAccount.firebaseId,
session: G.playerAccount.session,
sessionId: G.playerAccount.sessionId
};
callApi(upgradeCheckRequest, successCallback2, errorCallback2);
}
function api_checkNotifications(successCallback2, errorCallback2) {
const notifications = {
cmd: "player_notifications",
firebase_id: G.playerAccount.firebaseId
};
callApi(notifications, successCallback2, errorCallback2);
}
function api_notification_mark_as_read(successCallback2, errorCallback2) {
const notifications = {
cmd: "notify_mark_as_complete",
firebase_id: G.playerAccount.firebaseId
};
callApi(notifications, successCallback2, errorCallback2);
}
function api_reward(reward, successCallback2, errorCallback2, closeCallback) {
var rewardRequest = {
cmd: "reward",
firebaseId: G.playerAccount.firebaseId,
rewardTag: reward.tag
};
callApi(rewardRequest, successCallback2, errorCallback2);
}
function api_inGameReward(successCallback2, errorCallback2, reachedDailyLimitCallback) {
const inGameReward = {
cmd: "inGameReward",
firebaseId: G.playerAccount.firebaseId
};
const inGameRewardSuccessCallback = (rewardResults) => {
console.log("In Game reward response: " + rewardResults.result);
vueApp.hideSpinner();
switch (rewardResults.result) {
case "SUCCESS":
case "SUCCESS_FIRST":
successCallback2();
break;
case "REACHED_DAILY_LIMIT":
reachedDailyLimitCallback();
break;
case "ERROR":
errorCallback2();
break;
}
};
vueApp.showSpinner();
callApi(inGameReward, inGameRewardSuccessCallback, errorCallback2);
}
function api_urlReward(reward, successCallback2, errorCallback2) {
const giveReward = {
cmd: "urlRewardParams",
reward,
firebaseId: G.playerAccount.firebaseId
};
callApi(giveReward, successCallback2, errorCallback2);
}
function api_getPlayerSubStatus(successCallback2, errorCallback2) {
const getSubStatus = {
cmd: "getPlayerSubStatus",
playerId: G.playerAccount.id
};
const successfull = (results) => {
if (successCallback2)
successCallback2(results);
};
const errorfull = (results) => {
if (errorCallback2)
errorCallback2();
};
callApi(getSubStatus, successfull, errorfull);
}
function api_scheduledEvent(successCallback2, errorCallback2) {
const sendData = {
cmd: "getScheduledEventData"
};
callApi(sendData, successCallback2, errorCallback2);
}
function api_twitchPlayerEntitlements(successCallback2, errorCallback2) {
const checkEntitlements = {
cmd: "checkTwitchEntitlements",
playerId: G.playerAccount.id,
firebaseId: G.playerAccount.firebaseId
};
callApi(checkEntitlements, successCallback2, errorCallback2);
}
function api_incentivizedVideoRewardRequest(successCallback2, errorCallback2) {
if (!AIPVideoAds.isChwRequest) {
console.log("api_incentivizedVideoRewardRequest() API called directly. chw not played");
return;
}
const incentivizedVideoReward = {
cmd: "incentivizedVideoReward",
token: servicesToken,
id: G.playerAccount.id,
firebaseId: G.playerAccount.firebaseId,
sessionId: G.playerAccount.sessionId
// sku: 'chicken_nugget_pass'
};
callApi(incentivizedVideoReward, successCallback2, errorCallback2);
}
function api_chicknWinnerPlayerRewardCheck(successCallback2, errorCallback2) {
const apiData = {
cmd: "chicknWinnerReady",
id: G.playerAccount.id,
sessionId: G.playerAccount.sessionId
};
callApi(apiData, successCallback2, errorCallback2);
}
function api_updatePlayerStats(successCallback2, errorCallback2) {
const apiData = {
cmd: "updatePlayerStats",
playerId: G.playerAccount.id
};
callApi(apiData, successCallback2, errorCallback2);
}
function api_checkAfterStorePurchase(transactionId, success, error) {
const data2 = {
cmd: "checkAfterStorePurchase",
playerId: G.playerAccount.id,
transactionId
};
callApi(data2, success, error);
}
var api_giveItemReward = (reward, successCallback2, errorCallback2) => callApi({ cmd: "urlRewardParams", reward, firebaseId: G.playerAccount.firebaseId }, successCallback2, errorCallback2);
function BulletActor(bullet) {
this.scene = bullet.scene;
this.bullet = bullet;
this.delayFrames = 0;
this.mesh_ = this.scene.getMeshByName("bullet").createInstance("");
this.mesh_.setEnabled(false);
}
BulletActor.prototype.fire = function(isBig) {
this.delayFrames = 3;
if (isBig) {
this.mesh_.scaling.x = 2;
this.mesh_.scaling.y = 2;
} else {
this.mesh_.scaling.x = 1;
this.mesh_.scaling.y = 1;
}
this.mesh_.position.x = this.bullet.x;
this.mesh_.position.y = this.bullet.y;
this.mesh_.position.z = this.bullet.z;
this.mesh_.lookAt(
new BABYLON.Vector3(
this.bullet.x + this.bullet.dx,
this.bullet.y + this.bullet.dy,
this.bullet.z + this.bullet.dz
)
);
this.mesh_.scaling.z = 0.5;
};
BulletActor.prototype.update = function(delta) {
if (this.delayFrames > 0) {
this.delayFrames--;
} else {
this.mesh_.setEnabled(true);
}
this.mesh_.position.x += (this.bullet.x - this.mesh_.position.x) * 0.5;
this.mesh_.position.y += (this.bullet.y - this.mesh_.position.y) * 0.5;
this.mesh_.position.z += (this.bullet.z - this.mesh_.position.z) * 0.5;
if (this.bullet.player_.id != meId) {
this.mesh_.scaling.z = Math.min(this.mesh_.scaling.z + 0.03, 3);
}
};
BulletActor.prototype.remove = function() {
this.mesh_.setEnabled(false);
};
var Chw = class {
constructor(end, span, count) {
this.watchedCount = 0;
this.days = 0;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.progress = 1;
this.timer = null;
this.gap = 0;
this.end = end;
this.span = span;
this.limitReached = false;
this.ready = false;
this.count = count;
}
set count(val) {
if (this.watchedCount !== val) {
this.watchedCount = val;
if (this.watchedCount > CHICKWINNER.dailyLimit) {
this.limitReached = true;
} else {
this.limitReached = false;
}
}
this.chwTimer();
}
get count() {
return this.watchedCount;
}
chwClearTimer() {
if (this.timer !== null && this.ready) {
clearInterval(this.timer);
this.timer = null;
}
}
chwTimer() {
if (this.timer === null) {
this.timer = setInterval(() => this.chwData(), 1e3);
}
}
chwData() {
this.gap = Math.floor(this.end - Math.trunc(Date.now() / 1e3));
this.progress = Math.floor((this.span - this.gap) / this.span * 100);
if (this.gap < 0) {
this.gap = 0;
this.progress = 100;
}
let hoursLeft = 0;
let minutesLeft = 0;
if (this.progress < 100) {
this.days = Math.floor(this.gap / 24 / 60 / 60);
hoursLeft = Math.floor(this.gap - this.days * 86400);
this.hours = Math.floor(hoursLeft / 3600);
minutesLeft = Math.floor(hoursLeft - this.hours * 3600);
this.minutes = Math.floor(minutesLeft / 60);
this.seconds = this.gap % 60;
} else {
this.ready = true;
this.chwClearTimer();
}
vueApp.chwUiTimerUpdate(this.hours, this.minutes, this.seconds, this.progress, this.ready, this.limitReached, this.watchedCount);
}
};
var tv1 = new BABYLON.Vector3();
var tv2 = new BABYLON.Vector3();
var respawnTime;
var uiCamera;
var shellFragManager;
var shellBurstManager;
var yolkSplatManager;
var chatting;
var mapOverviewAxis = 0;
var spectator;
var spectateKeepAlive;
var lastTimeStamp;
var chatEvents;
var chatContainer;
var respawnVideoPlayed;
var respawnInterval;
var setNewTimerStart;
var equipmentWasChanged = false;
var playerHistory;
var cameraDirection = new BABYLON.Vector3();
var capZoneMeshes;
var pAudio;
var explosionSmokeManager;
var explosionFireManager;
var grenadePowerUp;
var mapOverview;
var scope;
var reticle;
var hitIndicator;
var hitMarkers;
var spectate;
var spectateMode;
var controlKeys;
var kills;
var deaths;
var bestOverallStreak;
var logicInterval;
var now;
var gameScene;
var map;
var minMap;
var shadowLight;
var viewingPlayer;
var grenadeThrowPower;
var players;
var nameTexture;
var nameSprites;
var auraSprites;
var mapMesh;
var spatula;
var ignoreFirstMouseMove;
var roundEnded = false;
var playerCount = [0, 0, 0];
function setupLights() {
gameScene.clearColor = BABYLON.Color3.Black();
shadowLight = new BABYLON.DirectionalLight("", new BABYLON.Vector3(0, -1, 0), gameScene);
shadowLight.lightmapMode = BABYLON.Light.LIGHTMAP_SHADOWSONLY;
shadowLight.intensity = 1.2;
shadowLight.autoUpdateExtends = false;
shadowLight.shadowMinZ = 0.05;
shadowLight.shadowMaxZ = 40;
shadowLight.shadowFrustumSize = 15;
shadowGen = new BABYLON.ShadowGenerator(1024 * 1, shadowLight);
shadowGen.forceBackFacesOnly = true;
}
function startGame() {
console.log("startGame()");
var oneSignalBell = document.getElementById("onesignal-bell-container");
setNewTimerStart = Date.now();
if (oneSignalBell) {
oneSignalBell.style.display = "none";
}
respawnVideoPlayed = false;
players = [];
playerHistory = [];
respawnTime = -1;
vueApp.game.respawnTime = 0;
me = null;
viewingPlayer = null;
grenadePowerUp = false;
spatula = null;
controlKeys = 0;
gamePaused = true;
roundEnded = false;
spectate = false;
spectator = new Spectator();
lastTimeStamp = performance.now();
ping = 0;
highestPing = 0;
pingTotal = 0;
pingSamples = 0;
fpsTotal = -1;
fpsSamples = 0;
fpsAverage = 0;
chatEvents = 0;
kills = 0;
deaths = 0;
bestOverallStreak = 0;
gameStartTime = Date.now();
nextPingSample = Date.now() + 1e3;
G.engine.clear(BABYLON.Color3.Black());
G.engine.stopRenderLoop();
gameScene = new BABYLON.Scene(G.engine);
if (!settings.autoDetail)
gameScene.shadowsEnabled = settings.shadowsEnabled;
gameScene.autoClear = true;
gameScene.autoClearDepthAndStencil = true;
setupLights();
camera = new BABYLON.TargetCamera("camera", BABYLON.Vector3.Zero(), gameScene);
gameScene.activeCameras.push(camera);
camera.maxZ = 100;
camera.fov = 1.25;
camera.minZ = 0.05;
BAWK.attach(camera.globalPosition, cameraDirection);
uiCamera = new BABYLON.FreeCamera("uiCamera", new BABYLON.Vector3(0, 0, -1), gameScene);
uiCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
uiCamera.layerMask = 536870912;
uiCamera.autoClear = false;
gameScene.activeCameras.push(uiCamera);
nameTexture = new BABYLON.DynamicTexture("", 2048, gameScene, true, 2);
nameSprites = new BABYLON.SpriteManager("", "", 18, { width: 512, height: 256 }, gameScene);
nameSprites.fogEnabled = false;
nameSprites.texture = nameTexture;
auraSprites = new BABYLON.SpriteManager("", "img/particles.png?" + version, 18, 128, gameScene);
auraSprites.fogEnabled = true;
loadMaterials(gameScene);
window.onfocus = function() {
lastTimeStamp = performance.now();
if (me)
refreshGameState();
};
window.onblur = function() {
};
document.onpointerlockchange = function() {
if (!document.pointerLockElement && me) {
lastKey = null;
controlKeys = 0;
me.controlKeys = 0;
me.releaseTrigger();
setTimeout(() => {
var out = CommOut.getBuffer();
out.packInt8(CommCode.pause);
out.send(ws);
me.resetCountdowns();
let rSpawnTimer = adBlocker && !G.productBlockAds && !pokiActive ? 10 : 5;
setRespawnTime(rSpawnTimer);
}, 100);
gamePaused = true;
vueApp.statsLoading();
timeout.set(function() {
me.removeFromPlay();
updateStats();
}, 3e3);
console.log("pausing game via pointerlock exit");
pauseGame();
pokiGamePlayStop();
if (crazyGamesActive)
crazysdk.gameplayStop();
}
};
document.body.style.overflow = "hidden";
InputQueue.init();
loadMap(mapIdx, onLoadingComplete);
if (tutorialShowing) {
vueApp.setDarkOverlay(true);
tutorialShowing = false;
}
}
function pausePlayerGame(key) {
if (chatting)
return;
if (inGame && !gamePaused && document.pointerLockElement) {
document.exitPointerLock();
console.log("pausing game on key: ", key);
}
}
function openGameMenu() {
if (document.pointerLockElement) {
console.log("pausing game and breaking pointerlock");
document.exitPointerLock();
} else {
console.log("pausing game via esc key");
pauseGame();
}
}
function testGameUI() {
vueApp.hideGameMenu();
document.getElementById("deathBox").style.display = "none";
document.getElementById("weaponBox").style.display = "block";
document.getElementById("healthContainer").style.display = "block";
document.getElementById("hardBoiledContainer").style.display = "block";
document.getElementById("killTicker").style.display = "block";
if (chatting)
chatInEl.focus();
doFirstPersonCamera();
reticle.show();
document.getElementById("gameAdContainer").style.display = "none";
}
function pauseGame() {
if (vueApp.showScreen === vueApp.screens.equip)
return;
gamePaused = true;
spectate = false;
interval.clear(spectateKeepAlive);
ignoreFirstMouseMove = true;
updateActorTeams();
removeCanvasListeners();
vueApp.setPause(gamePaused);
vueApp.showGameMenu();
document.getElementById("grenadeThrowContainer").style.visibility = "hidden";
document.getElementById("weaponBox").style.display = "none";
document.getElementById("healthContainer").style.display = "none";
document.getElementById("hardBoiledContainer").style.display = "none";
document.getElementById("killTicker").style.display = "none";
document.getElementById("spectate").style.display = "none";
document.getElementById("serverAndMapInfo").style.display = "block";
document.getElementById("captureIconContainer").style.display = "none";
document.getElementById("playerList").style.pointerEvents = "auto";
const gameAdContainer = document.getElementById("gameAdContainer");
if (gameAdContainer)
gameAdContainer.style.display = "block";
reticle.hide();
reticle.hideDot();
if (chatting)
chatInEl.focus();
newGameStart = false;
if (!chatContainer)
chatContainer = document.querySelector(".chat-container");
setTimeout(() => {
chatContainer.scrollTop = chatContainer.scrollHeight;
resize();
}, 300);
}
function resumeGame() {
console.log("resumeGame called");
if (me) {
gamePaused = false;
vueApp.hideGameMenu();
document.getElementById("deathBox").style.display = "none";
document.getElementById("killTicker").style.display = "block";
document.getElementById("serverAndMapInfo").style.display = "none";
if (gameType == GameType.king)
document.getElementById("captureIconContainer").style.display = "block";
document.getElementById("playerList").style.pointerEvents = "none";
if (!spectate) {
document.getElementById("weaponBox").style.display = "block";
document.getElementById("healthContainer").style.display = "block";
document.getElementById("hardBoiledContainer").style.display = "block";
updateHealthUI();
} else {
document.getElementById("spectate").style.display = "block";
}
const gameAdContainer = document.getElementById("gameAdContainer");
if (gameAdContainer)
gameAdContainer.style.display = "block";
addCanvasListeners();
if (chatting)
chatInEl.focus();
setTimeout(() => {
resize();
}, 300);
saveEquipment();
}
}
function setRespawnTime(sec) {
respawnTime = Math.max(sec, respawnTime);
vueApp.game.respawnTime = respawnTime;
if (respawnInterval)
interval.clear(respawnInterval);
respawnInterval = interval.set(function() {
respawnTime--;
vueApp.game.respawnTime = Math.min(respawnTime, sec);
if (respawnTime <= 0 && inGame) {
respawnTime = -1;
interval.clear(respawnInterval);
doMapOverviewCamera();
}
}, 1200);
}
var munitionsManager;
var itemManager;
var lastMouseMovement = {};
function respawn() {
if (playOffline) {
me.playing = true;
canvas.requestPointerLock({ unadjustedMovement: settings.fastPollMouse });
return;
}
console.log("Respawn pressed - respawnTime: " + respawnTime);
if (respawnTime < 0) {
interval.clearAll();
timeout.clearAll();
interval.set(() => {
if (document.activeElement.tagName == "IFRAME") {
console.log("iframe attempted to steal focus:", document.activeElement);
document.activeElement.blur();
}
}, 100);
if (settings.autoDetail)
enableAutoDetail();
if (isTimeToPlayVideoAd()) {
respawnVideoPlayed = true;
AIPVideoAds.play("shellshock.io_preroll", openGameMenu);
return;
}
return requestRespawn();
}
}
function isTimeToPlayVideoAd() {
if (G.productBlockAds) {
return false;
}
if (respawnVideoPlayed)
return false;
let timeout2 = adTest ? 3e4 : 24e4;
if (pokiActive)
timeout2 = 0;
let adReady = false;
if (hasTimesPlayed || timesPlayed > 1) {
adReady = true;
}
const lastPreRoll = getStoredNumber("lastPreRoll", Date.now()), whenToPlay = lastPreRoll + timeout2, timeForAd = adReady && deaths > 1 && Date.now() > whenToPlay;
let metaTimeForAd = metaGameUI.timeToPlayVideoAd();
if (metaTimeForAd === true)
return true;
if (metaTimeForAd === false)
return false;
if (!timeForAd)
return false;
return true;
}
var requestRespawnBlocked = false;
function requestRespawn() {
console.log(`requestRespawnBlocked ${requestRespawnBlocked}`);
if (requestRespawnBlocked)
return;
requestRespawnBlocked = true;
setTimeout(() => requestRespawnBlocked = false, 1e3);
if (equipmentWasChanged) {
me.changeCharacter(
G.playerAccount.classIdx,
G.playerAccount.getPrimaryWeapon(),
G.playerAccount.getSecondaryWeapon(),
G.playerAccount.colorIdx,
G.playerAccount.hatItem,
G.playerAccount.stampItem,
G.playerAccount.grenadeItem,
G.playerAccount.meleeItem,
0,
0
);
var out = CommOut.getBuffer();
out.packInt8(CommCode.changeCharacter);
out.packInt8(G.playerAccount.classIdx);
out.send(ws);
equipmentWasChanged = false;
}
var out = CommOut.getBuffer();
out.packInt8(CommCode.requestRespawn);
out.send(ws);
pokiGamePlayStart();
vueApp.setPause(false);
if (crazyGamesActive)
crazysdk.gameplayStart();
}
function onCanvasMouseDown(event) {
if (!document.pointerLockElement)
canvas.requestPointerLock({ unadjustedMovement: settings.fastPollMouse });
inputDown("keyboard", "MOUSE " + event.button);
if (event.button == 1)
event.preventDefault();
}
function onCanvasMouseUp(event) {
inputUp("keyboard", "MOUSE " + event.button);
}
function onCanvasMouseMove(event) {
if (document.pointerLockElement && !ignoreFirstMouseMove && me && (me.hp_ > 0 || spectate)) {
var mult = Math.pow(settings.mouseSpeed * 1e-3, 2);
if (me.scope)
mult *= me.weapon.actor.scopeFov;
var mx = event.movementX;
var my = event.movementY;
if (lastMouseMovement.x) {
if (Math.sign(mx) != Math.sign(lastMouseMovement.x)) {
mx = 0;
}
}
if (lastMouseMovement.y) {
if (Math.sign(my) != Math.sign(lastMouseMovement.y)) {
my = 0;
}
}
lastMouseMovement.x = mx;
lastMouseMovement.y = my;
me.yaw_ = Math.radAdd(me.yaw_, mx * mult);
me.pitch_ = Math.clamp(me.pitch_ + my * settings.mouseInvert * mult, -1.5, 1.5);
}
ignoreFirstMouseMove = false;
}
function onCanvasMouseWheel(event) {
if (event.wheelDelta > 0) {
inputDown("keyboard", "WHEEL UP");
inputUp("keyboard", "WHEEL UP");
} else {
inputDown("keyboard", "WHEEL DOWN");
inputUp("keyboard", "WHEEL DOWN");
}
}
var color4White = new BABYLON.Color4(1, 1, 1, 1);
function createParticleManager(filename, number, firstFrame, lastFrame, scene) {
var manager = new BABYLON.SpriteManager("", "img/" + filename + "?" + version, number, 128, scene);
for (var i2 = 0; i2 < number; i2++) {
var s = new BABYLON.Sprite("", manager);
s.isVisible = false;
}
manager.nextIdx = 0;
manager.getSprite = function(cell) {
var s2 = this.sprites[this.nextIdx];
s2.cellIndex = cell !== void 0 ? firstFrame + cell : Math.randomInt(firstFrame, lastFrame);
s2.isVisible = true;
s2.easing = Ease.linear;
s2.startSize = -1;
s2.endSize = -1;
s2.gravity = 0;
s2.dx = 0;
s2.dy = 0;
s2.dz = 0;
s2.float = 0;
s2.anim = 0;
s2.slow = 0;
s2.angle = 0;
s2.rotate = 0;
s2.stopped = false;
s2.animColors = null;
s2.collide = false;
s2.color.copyFrom(color4White);
this.nextIdx = ++this.nextIdx % this.sprites.length;
return s2;
};
return manager;
}
function addBulletHitSprite(x, y, z, dx, dy, dz) {
var s = explosionSmokeManager.getSprite(0);
s.animLength = Math.random() * 20 + 30;
s.easing = Ease.outQuint;
s.position.x = x;
s.position.y = y;
s.position.z = z;
s.dx = dx * 0.1;
s.dy = dy * 0.1;
s.dz = dz * 0.1;
s.startSize = 0.1;
s.endSize = Math.random() * 0.2 + 0.4;
s.angle = Math.random() * Math.PI2;
s.rotate = Math.random() * 0.08 - 0.04;
s.animColors = bulletHitColors;
}
function addExplosionSprite(manager, animLength, x, y, z, dx, dy, dz, size, gravity, byItem) {
let cell = 0;
let smokeCell = 0;
let fireColorName = "default";
let smokeColorName = "default";
if (byItem) {
cell = byItem.item_data.cell || 0;
if (manager == explosionSmokeManager) {
if (cell) {
smokeCell = byItem.item_data.smokeCell;
if (isNaN(smokeCell))
smokeCell = cell;
}
}
fireColorName = byItem.item_data.fireColors || "default";
smokeColorName = byItem.item_data.smokeColors || "default";
}
var s = manager.getSprite(cell);
s.animLength = animLength;
s.easing = Ease.inOutQuad;
s.position.x = x;
s.position.y = y;
s.position.z = z;
s.size = size;
s.dx = dx;
s.dy = dy;
s.dz = dz;
s.slow = 0.7;
s.angle = Math.random() * Math.PI2;
s.rotate = Math.random() * 0.04 - 0.02;
if (manager == explosionFireManager) {
s.animColors = fireColors[fireColorName];
} else {
s.animColors = smokeColors[smokeColorName];
}
return s;
}
function addExplosion(x, y, z, damage, radius, byItem) {
for (var i2 = 0; i2 < Math.floor(damage / 4); i2++) {
var animLength = Math.random() * 80 + 80;
var size = Math.random() * 1 + 0.5;
var se = (0.9 - size) * 0.5;
var dx = (Math.random() * 2 - 1) * se;
var dy = (Math.random() * 2 - 1) * se + 0.1;
var dz = (Math.random() * 2 - 1) * se;
var s = addExplosionSprite(explosionSmokeManager, animLength, x, y, z, dx, dy, dz, size, true, byItem);
s.float = Math.random() * 0.015 + 1e-3;
s.collide = true;
s = addExplosionSprite(explosionFireManager, animLength * 0.075, x, y, z, dx * 1.5, dy * 1.5, dz * 1.5, size, true, byItem);
s.collide = true;
}
if (me) {
var d = Math.length3(me.x_ - x, me.y_ - y, me.z_ - z);
radius *= 1.5;
if (d < radius) {
var shakeFactor = Math.max(0, (radius - d) / radius);
shake = Math.min(7, shake + shakeFactor * 6);
}
}
}
var fireColors = {
default: [
{ pos: 0, color: new BABYLON.Color4(1, 0.9, 0.8, 1) },
{ pos: 0.2, color: new BABYLON.Color4(1, 0.5, 0.1, 1) },
{ pos: 0.4, color: new BABYLON.Color4(0.6, 0.2, 0.1, 1) },
{ pos: 0.7, color: new BABYLON.Color4(0, 0, 0, 0) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
rainbow: [
{ pos: 0, color: new BABYLON.Color4(1, 0.1, 0.1, 1) },
{ pos: 0.2, color: new BABYLON.Color4(1, 1, 0.1, 1) },
{ pos: 0.4, color: new BABYLON.Color4(0.1, 1, 0.1, 1) },
{ pos: 0.7, color: new BABYLON.Color4(0.1, 0.1, 1, 0.5) },
{ pos: 1, color: new BABYLON.Color4(1, 0.1, 1, 0) }
],
gold: [
{ pos: 0, color: new BABYLON.Color4(1, 1, 0.3, 1) },
{ pos: 0.4, color: new BABYLON.Color4(1, 0.8, 0.2, 1) },
//{ pos: 0.7, color: new BABYLON.Color4(1, 0.6, 0.1, 0) },
{ pos: 1, color: new BABYLON.Color4(1, 0.6, 0.1, 0) }
],
corrupt: [
{ pos: 0, color: new BABYLON.Color4(1, 0.1, 0.1, 1) },
{ pos: 0.3, color: new BABYLON.Color4(1, 1, 1, 1) },
{ pos: 0.6, color: new BABYLON.Color4(1, 0.1, 0.1, 1) },
{ pos: 1, color: new BABYLON.Color4(1, 1, 1, 0) }
],
thermal: [
{ pos: 0, color: new BABYLON.Color4(1, 0.9, 0.8, 1) },
{ pos: 0.2, color: new BABYLON.Color4(1, 0.5, 0.1, 1) },
{ pos: 0.4, color: new BABYLON.Color4(0.6, 0.2, 0.1, 1) },
{ pos: 0.5, color: new BABYLON.Color4(1, 1, 1, 1) },
{ pos: 0.6, color: new BABYLON.Color4(1, 1, 1, 0) },
{ pos: 0.7, color: new BABYLON.Color4(1, 1, 1, 1) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
black: [
{ pos: 0, color: new BABYLON.Color4(0, 0, 0, 1) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
red: [
{ pos: 0, color: new BABYLON.Color4(1, 0.7, 0.3, 1) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
blue: [
{ pos: 0, color: new BABYLON.Color4(0.3, 0.7, 1, 1) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
]
};
var smokeColors = {
default: [
{ pos: 0, color: new BABYLON.Color4(0.3, 0.3, 0.3, 1) },
{ pos: 1, color: new BABYLON.Color4(0.7, 0.7, 0.7, 0) }
],
white: [
{ pos: 0, color: new BABYLON.Color4(1, 1, 1, 0.5) },
{ pos: 1, color: new BABYLON.Color4(1, 1, 1, 0) }
],
corrupt: [
{ pos: 0, color: new BABYLON.Color4(1, 1, 1, 0.6) },
{ pos: 0.5, color: new BABYLON.Color4(1, 0.1, 0.1, 0.4) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
thermal: [
{ pos: 0, color: new BABYLON.Color4(0.5, 0.1, 0.01, 0.3) },
{ pos: 0.3, color: new BABYLON.Color4(0.7, 0.4, 0, 0.1) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
supernova: [
{ pos: 0, color: new BABYLON.Color4(1, 1, 1, 0.5) },
{ pos: 1, color: new BABYLON.Color4(1, 0, 1, 0) }
],
black: [
{ pos: 0, color: new BABYLON.Color4(0, 0, 0, 1) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
softblack: [
{ pos: 0, color: new BABYLON.Color4(0, 0, 0, 0.5) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
red: [
{ pos: 0, color: new BABYLON.Color4(1, 0.7, 0.3, 1) },
{ pos: 0.5, color: new BABYLON.Color4(1, 0.3, 0, 0.6) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
],
blue: [
{ pos: 0, color: new BABYLON.Color4(0.3, 0.7, 1, 1) },
{ pos: 0.5, color: new BABYLON.Color4(0, 0.3, 1, 0.6) },
{ pos: 1, color: new BABYLON.Color4(0, 0, 0, 0) }
]
};
var bulletHitColors = [
{ pos: 0, color: new BABYLON.Color4(1, 1, 1, 1) },
{ pos: 0.2, color: new BABYLON.Color4(0.7, 0.7, 0.7, 0.7) },
{ pos: 1, color: new BABYLON.Color4(0.7, 0.7, 0.7, 0) }
];
var shellHitColors = [
{ pos: 0, color: new BABYLON.Color4(1, 1, 1, 1) },
{ pos: 0.8, color: new BABYLON.Color4(1, 1, 1, 1) },
{ pos: 1, color: new BABYLON.Color4(1, 1, 1, 0) }
];
function lerp(colors, p, ref) {
for (var i2 = colors.length - 2; i2 >= 0; i2--) {
if (p >= colors[i2].pos) {
BABYLON.Color4.LerpToRef(colors[i2].color, colors[i2 + 1].color, (p - colors[i2].pos) * (1 / (colors[i2 + 1].pos - colors[i2].pos)), ref);
return;
}
}
}
function shellBurst(player, count, theSize, theAnimLength) {
for (var i2 = 0; i2 < count; i2++) {
var animLength = Math.random() * theAnimLength + theAnimLength * 0.5;
var size = i2 / (count * 0.5) * theSize + theSize * 0.5;
var se = 0.08 / (size + 1);
var dx = (Math.random() * 2 - 1) * se;
var dy = (Math.random() * 2 - 0.5) * se;
var dz = (Math.random() * 2 - 1) * se;
var s = shellBurstManager.getSprite();
s.animLength = animLength;
s.easing = Ease.inQuad;
s.position.x = player.actor.mesh_.position.x;
s.position.y = player.actor.mesh_.position.y + 0.3;
s.position.z = player.actor.mesh_.position.z;
s.startSize = size;
s.endSize = 0;
s.gravity = 3e-3;
s.dx = dx;
s.dy = dy;
s.dz = dz;
s.angle = Math.random() * Math.PI2;
s.rotate = Math.random() * 0.2 - 0.1;
s.collide = true;
s.color.r = player.actor.bodyMesh_.colorMult.r;
s.color.g = player.actor.bodyMesh_.colorMult.g;
s.color.b = player.actor.bodyMesh_.colorMult.b;
}
}
function yolkBurst(player) {
var count = 10;
var theSize = 0.2;
for (var i2 = 0; i2 < count; i2++) {
var animLength = Math.random() * 80 + 80;
var size = i2 / (count * 0.5) * theSize + theSize;
var se = 0.05 / (size + 1);
var dx = (Math.random() * 2 - 1) * se;
var dy = (Math.random() * 2 - 0.25) * se * 1.5;
var dz = (Math.random() * 2 - 1) * se;
var s = yolkManager.getSprite();
s.animLength = animLength;
s.easing = Ease.inQuad;
s.position.x = player.actor.mesh_.position.x;
s.position.y = player.actor.mesh_.position.y + 0.3;
s.position.z = player.actor.mesh_.position.z;
s.startSize = size;
s.endSize = 0;
s.gravity = 5e-3;
s.dx = dx;
s.dy = dy;
s.dz = dz;
s.slow = 0.9;
s.angle = Math.random() * Math.PI2;
s.rotate = Math.random() * 0.2 - 0.1;
s.collide = true;
}
}
function yolkSplat(player, dmg) {
var count = Math.floor(dmg / 33) + 1;
for (var i2 = 0; i2 < count; i2++) {
var animLength = Math.random() * 9 + 9;
var size = 0.8;
var se = 0.03 / (size + 1);
var dx = (Math.random() * 2 - 1) * se;
var dy = (Math.random() * 2 - 0.25) * se * 1.5;
var dz = (Math.random() * 2 - 1) * se;
tv1.set(me.x_, me.y_, me.z_);
tv2.set(player.x_, player.y_, player.z_);
tv1.subtractInPlace(tv2).normalize().scaleInPlace(0.26);
var s = yolkSplatManager.getSprite();
s.animLength = animLength;
s.easing = Ease.linear;
s.position.x = player.actor.mesh_.position.x;
s.position.y = player.actor.mesh_.position.y + 0.3;
s.position.z = player.actor.mesh_.position.z;
s.startSize = size * 0.2;
s.endSize = size;
s.gravity = 3e-3;
s.dx = dx + player.dx;
s.dy = dy;
s.dz = dz + player.dz;
s.slow = 0.95;
s.angle = Math.random() * Math.PI2;
s.rotate = Math.random() * 0.02 - 1e-3;
s.collide = false;
s.animColors = shellHitColors;
}
}
function shellFrag(player, dmg) {
var count = Math.floor(dmg / 33) + 1;
for (var i2 = 0; i2 < count; i2++) {
var animLength = Math.random() * 9 + 9;
var size = 0.8;
var se = 0.03 / (size + 1);
var dx = (Math.random() * 2 - 1) * se;
var dy = (Math.random() * 2 - 0.25) * se * 1.5;
var dz = (Math.random() * 2 - 1) * se;
tv1.set(me.x_, me.y_, me.z_);
tv2.set(player.x_, player.y_, player.z_);
tv1.subtractInPlace(tv2).normalize().scaleInPlace(0.26);
var s = shellFragManager.getSprite();
s.animLength = animLength;
s.easing = Ease.linear;
s.position.x = player.actor.mesh_.position.x;
s.position.y = player.actor.mesh_.position.y + 0.3;
s.position.z = player.actor.mesh_.position.z;
s.startSize = size * 0.2;
s.endSize = size;
s.gravity = 3e-3;
s.dx = dx + player.dx;
s.dy = dy;
s.dz = dz + player.dz;
s.slow = 0.95;
s.angle = Math.random() * Math.PI2;
s.rotate = Math.random() * 0.02 - 1e-3;
s.collide = false;
s.animColors = shellHitColors;
}
}
function updateParticles(manager, delta) {
for (var i2 = 0; i2 < manager.sprites.length; i2++) {
var s = manager.sprites[i2];
if (s.isVisible) {
var anim = s.easing(s.anim);
if (s.endSize >= 0) {
s.size = s.startSize + anim * (s.endSize - s.startSize);
}
if (s.animColors) {
lerp(s.animColors, anim, s.color);
}
if (!s.stopped) {
s.position.x += s.dx * delta;
s.position.y += s.dy * delta + s.float;
s.position.z += s.dz * delta;
if (s.rotate)
s.angle += s.rotate * delta;
var res = false;
if (s.collide) {
tv1.set(s.position.x, s.position.y, s.position.z);
res = Collision.pointCollidesWithStructure(tv1, true);
}
if (res) {
s.stopped = true;
s.position.x -= s.dx * delta;
s.position.y -= s.dy * delta;
s.position.z -= s.dz * delta;
} else if (s.gravity) {
s.dy -= s.gravity * delta;
}
if (s.slow) {
s.dx *= Math.pow(s.slow, delta);
s.dy *= Math.pow(s.slow, delta);
s.dz *= Math.pow(s.slow, delta);
}
}
s.anim += delta / s.animLength;
if (s.anim >= 1)
s.isVisible = false;
}
}
}
function onLoadingComplete() {
console.log("onLoadingComplete");
pAudio = new PositionalAudio({ numChannels: 24 }, { distanceModel: "exponential" });
try {
scope = new Scope();
hitIndicator = new HitIndicator();
hitMarkers = new HitMarkers(gameScene);
if (settings.hitMarkers) {
hitMarkers.show();
} else {
hitMarkers.hide();
}
reticle = new Reticle();
reticle.hide();
reticle.hideDot();
cloneMesh("muzzleFlash", gameScene, null, gameScene.getMaterialByName("muzzleFlash")).setEnabled(false);
cloneMesh("bullet", gameScene, null, gameScene.getMaterialByName("bullet")).setEnabled(false);
cloneMesh("rocket", gameScene, null, gameScene.getMaterialByName("standardInstanced")).setEnabled(false);
cloneMesh("ammo", gameScene, null, gameScene.getMaterialByName("standardInstanced")).setEnabled(false);
cloneMesh("grenadeItem", gameScene, null, gameScene.getMaterialByName("standardInstanced")).setEnabled(false);
cloneMesh("meleeItem", gameScene, null, gameScene.getMaterialByName("standardInstanced")).setEnabled(false);
cloneMesh("spatula", gameScene, null, gameScene.getMaterialByName("emissive")).setEnabled(false);
for (let i2 = 0; i2 < G.catalog.grenades.length; i2++) {
let name = G.catalog.grenades[i2].item_data.meshName;
cloneMesh(name, gameScene, null, gameScene.getMaterialByName("emissive")).setEnabled(false);
}
munitionsManager = new MunitionsManager(gameScene);
itemManager = new ItemManager();
explosionSmokeManager = createParticleManager("particles.png", 300, 16, 23, gameScene);
explosionSmokeManager.fogEnabled = true;
explosionSmokeManager.noAlphaTest = true;
explosionFireManager = createParticleManager("particles.png", 300, 16, 23, gameScene);
explosionFireManager.fogEnabled = true;
explosionFireManager.blendMode = BABYLON.Engine.ALPHA_ADD;
shellBurstManager = createParticleManager("particles.png", 400, 3, 6, gameScene);
shellBurstManager.fogEnabled = true;
yolkManager = createParticleManager("particles.png", 100, 2, 2, gameScene);
yolkManager.fogEnabled = true;
vueApp.switchToGameUi();
if (G.playerAccount.isUpgraded()) {
document.getElementById("chickenBadge").style.display = "block";
}
shellFragManager = createParticleManager("particles.png", 20, 0, 0, gameScene);
shellFragManager.fogEnabled = true;
yolkSplatManager = createParticleManager("particles.png", 20, 7, 7, gameScene);
yolkSplatManager.fogEnabled = true;
if (playOffline) {
meId = 0;
metaGameUI = {
update: () => {
},
render: () => {
}
};
metaGame = {
update: () => {
}
};
var playerData = {
id_: 0,
uniqueId_: 0,
name_: "Test",
charClass_: 0,
team_: 0,
primaryWeaponItem_: G.playerAccount.getPrimaryWeapon(),
secondaryWeaponItem_: G.playerAccount.getSecondaryWeapon(),
shellColor_: 0,
hatItem_: null,
stampItem_: null,
score_: 0,
kills_: 0,
deaths_: 0,
streak_: 0,
totalKills_: 0,
totalDeaths_: 0,
bestGameStreak_: 0,
bestOverallStreak_: 0,
x_: mapTest.x + 0.5,
y_: mapTest.y - 0.32,
z_: mapTest.z + 0.5,
dx_: 0,
dy_: 0,
dz_: 0,
frame_: 0,
pitch_: mapTest.pitch,
yaw_: mapTest.yaw,
shield_: 0,
hp_: 0,
playing_: false,
weaponIdx_: 0,
controlKeys_: 0,
randomSeed_: 0,
upgradeProductId_: G.playerAccount.upgradeProductId !== void 0 && G.playerAccount.upgradeProductId !== null ? G.playerAccount.upgradeProductId : 0,
activeShellStreaks_: 0,
social_: [],
hideBadge_: 0,
damageMod_: 1
};
playerData.stats_ = {};
StatsArr.forEach((stat) => playerData.stats_[stat] = 0);
addPlayer(playerData);
players[meId].hp_ = 100;
doFirstPersonCamera();
startRendering();
startRunning();
openGameMenu();
reticle.show();
reticle.showDot();
respawnTime = -1;
fpsTotal = 0;
vueApp.delayTheCracking = true;
} else {
mapOverview = true;
setUpSocket();
var out = CommOut.getBuffer();
out.packInt8(CommCode.clientReady);
out.send(ws);
pingStartTime = Date.now();
isItTimeForPokiReward();
const chatShareLinkText = `${getLocText("ingame_chat_msg")}
${getLocText("ingame_chat_msg_2")}`;
addChat(chatShareLinkText, null, inviteFriendsChat, "");
}
} catch (e2) {
console.log(e2);
}
}
function inviteFriendsChat() {
ga("send", "event", "game", "click", "openShareLinkChat");
inviteFriends();
}
function doMapOverviewCamera() {
camera.parent = null;
camera.position = new BABYLON.Vector3(0, map.height + 1, 0);
camera.lockedTarget = null;
camera.setTarget(new BABYLON.Vector3(map.width / 2, map.height / 4, map.depth / 2));
mapOverview = true;
viewingPlayer = me;
viewingPlayerId = meId;
gameScene.autoClear = true;
gameScene.autoClearDepthAndStencil = true;
}
function doFirstPersonCamera(player) {
camera.position = BABYLON.Vector3.Zero();
camera.rotation = BABYLON.Vector3.Zero();
if (player) {
camera.parent = player.actor.eye;
} else {
camera.parent = me.actor.eye;
}
camera.lockedTarget = null;
mapOverview = false;
gameScene.autoClear = false;
gameScene.autoClearDepthAndStencil = false;
}
var enterSpectatorModeBlocked = false;
function enterSpectatorMode() {
if (enterSpectatorModeBlocked)
return;
enterSpectatorModeBlocked = true;
setTimeout(() => enterSpectatorModeBlocked = false, 1e3);
if (respawnTime < 0) {
mapOverview = false;
spectate = true;
spectateMode = Spectate.freeCamera;
vueApp.setPause(false);
vueApp.setInGame(spectate);
spectator.freeCamera();
resumeGame();
canvas.requestPointerLock({ unadjustedMovement: settings.fastPollMouse });
me.yaw_ = Math.radRange(camera.rotation.y);
me.pitch_ = Math.radRange(camera.rotation.x);
spectateKeepAlive = interval.set(function() {
var out = CommOut.getBuffer();
out.packInt8(CommCode.keepAlive);
out.send(me.ws);
}, 15e3);
updateActorTeams();
}
}
function startRendering(ignoreResize) {
if (!hasValue(ignoreResize)) {
resize();
}
G.engine.runRenderLoop(function() {
updateActors();
if (viewingPlayer) {
shadowLight.position.x = viewingPlayer.x_;
shadowLight.position.y = viewingPlayer.y_ + 2;
shadowLight.position.z = viewingPlayer.z_;
}
gameScene.render();
metaGameUI.render();
});
}
function startRunning() {
captureKeys();
if (mapOverview)
doMapOverviewCamera();
logicInterval = setInterval(updateLogic, 1e3 / 30);
}
var killDisplayTimeout;
var chatParser = document.createElement("DIV");
var prevCmd = [];
var musicMetadata = "";
var isMusic = false;
var checkMusicChange = (metadata) => {
if (!isMusic && metadata) {
isMusic = true;
vueApp.musicWidget(true);
} else if (isMusic && !metadata) {
isMusic = false;
vueApp.musicWidget(false);
}
if (musicMetadata === metadata) {
return;
}
musicMetadata = metadata;
var json = decodeURI(metadata);
console.log("Music metadata", json);
data = JSON.parse(json);
vueApp.music.serverTracks = data;
if (location.host == "localhost" || location.host == "localshelldev.bluewizard.com") {
vueApp.music.serverTracks.albumArt = "https://shellshock.io/data/img/albumArt/" + data.id + data.albumExt + "?" + data.query;
} else {
vueApp.music.serverTracks.albumArt = dynamicContentPrefix + "data/img/albumArt/" + data.id + data.albumExt + "?" + data.query;
}
vueApp.songChanged = true;
};
function setUpSocket() {
ws.onmessage = function(e2) {
CommIn.init(e2.data);
var len;
while (len = CommIn.isMoreDataAvailable()) {
var cmd2 = CommIn.unPackInt8U();
switch (cmd2) {
case CommCode.playerInfo:
var playerId = CommIn.unPackInt8U();
var dbId = CommIn.unPackString(128);
var ip = CommIn.unPackString(32);
var player = players[playerId];
if (player) {
player.dbId = dbId;
player.ip = ip;
for (var i2 = 0; i2 < playerHistory.length; i2++) {
if (playerHistory[i2].id === playerId) {
playerHistory[i2].dbId = dbId;
playerHistory[i2].ip = ip;
break;
}
}
}
break;
case CommCode.musicInfo:
var metadata = CommIn.unPackLongString();
checkMusicChange(metadata);
break;
case CommCode.pause:
var playerId = CommIn.unPackInt8U();
var player = players[playerId];
if (player)
player.removeFromPlay();
break;
case CommCode.eventModifier:
console.log("eventModifier");
var out = CommOut.getBuffer();
out.packInt8(CommCode.eventModifier);
out.send(ws);
break;
case CommCode.clientReady:
newGameStart = true;
respawnTime = -1;
fpsTotal = 0;
startRendering();
startRunning();
vueApp.delayInGamePlayButtons();
let url = createInviteLink();
vueData.game.shareLinkPopup.url = url;
if (autoInvite) {
setTimeout(() => {
vueApp.onGamePauseUi();
vueApp.onGameOptionsClick();
}, 200);
} else {
openGameMenu();
}
if (settings.autoDetail) {
enableAutoDetail();
} else {
setHighRes(settings.highRes);
setShadows(settings.shadowsEnabled);
}
var out = CommOut.getBuffer();
out.packInt8(CommCode.ping);
out.send(ws);
break;
case CommCode.addPlayer:
var id = CommIn.unPackInt8U();
var uniqueId = CommIn.unPackString();
var name = CommIn.unPackString();
var charClass = CommIn.unPackInt8U();
name = fixStringWidth(name, 80);
var playerData = {
id_: id,
uniqueId_: uniqueId,
name_: name,
charClass_: charClass,
team_: CommIn.unPackInt8U(),
primaryWeaponItem_: G.catalog.findItemById(CommIn.unPackInt16U()),
secondaryWeaponItem_: G.catalog.findItemById(CommIn.unPackInt16U()),
shellColor_: CommIn.unPackInt8U(),
hatItem_: G.catalog.findItemById(CommIn.unPackInt16U()),
stampItem_: G.catalog.findItemById(CommIn.unPackInt16U()),
grenadeItem_: G.catalog.findItemById(CommIn.unPackInt16U()),
meleeItem_: G.catalog.findItemById(CommIn.unPackInt16U()),
x_: CommIn.unPackFloat(),
y_: CommIn.unPackFloat(),
z_: CommIn.unPackFloat(),
dx_: CommIn.unPackFloat(),
dy_: CommIn.unPackFloat(),
dz_: CommIn.unPackFloat(),
yaw_: CommIn.unPackRadU(),
pitch_: CommIn.unPackRad(),
score_: CommIn.unPackInt32U(),
kills_: CommIn.unPackInt16U(),
deaths_: CommIn.unPackInt16U(),
streak_: CommIn.unPackInt16U(),
totalKills_: CommIn.unPackInt32U(),
totalDeaths_: CommIn.unPackInt32U(),
bestGameStreak_: CommIn.unPackInt16U(),
bestOverallStreak_: CommIn.unPackInt16U(),
shield_: CommIn.unPackInt8U(),
hp_: CommIn.unPackInt8U(),
playing_: CommIn.unPackInt8U(),
weaponIdx_: CommIn.unPackInt8U(),
controlKeys_: CommIn.unPackInt8U(),
upgradeProductId_: CommIn.unPackInt8U(),
activeShellStreaks_: CommIn.unPackInt8U(),
social_: CommIn.unPackLongString(),
hideBadge_: CommIn.unPackInt8U()
};
playerData.gameData_ = {};
playerData.gameData_.mapIdx = CommIn.unPackInt8U();
playerData.gameData_.private = CommIn.unPackInt8U();
playerData.gameData_.gameType = CommIn.unPackInt8U();
playerData.stats_ = {};
StatsArr.forEach((stat) => playerData.stats_[stat] = 0);
playerData.stats_.kills = playerData.kills_;
playerData.stats_.deaths = playerData.deaths_;
playerData.stats_.streak = playerData.streak_;
playerData.name_ = filterUnicode(playerData.name_);
if (!players[playerData.id_]) {
if (meId == playerData.id_ || observingGame) {
playerData.normalName_ = playerData.name_;
playerData.safeName_ = playerData.name_;
} else {
playerData.normalName_ = playerData.name_.replace(/<|>/g, "");
playerData.safeName_ = generateRandomName();
if (playerData.normalName_.length == 0 || isBadWord(playerData.normalName_)) {
playerData.normalName_ = playerData.safeName_;
}
if (settings.safeNames) {
playerData.name_ = playerData.safeName_;
} else {
playerData.name_ = playerData.normalName_;
}
}
let historicPlayer = findPlayerByUniqueId(uniqueId);
if (historicPlayer) {
playerData.muted_ = historicPlayer.muted;
if (playerData.muted_ && !settings.safeNames)
playerData.name_ = playerData.safeName_;
} else {
playerData.muted_ = false;
}
addPlayer(playerData);
}
break;
case CommCode.removePlayer:
var playerId = CommIn.unPackInt8U();
removePlayer(playerId);
break;
case CommCode.spawnItem:
var id = CommIn.unPackInt16U();
var kind = CommIn.unPackInt8U();
var x = CommIn.unPackFloat();
var y = CommIn.unPackFloat();
var z = CommIn.unPackFloat();
itemManager.spawnItem(id, kind, x, y, z);
break;
case CommCode.collectItem:
var playerId = CommIn.unPackInt8U();
var kind = CommIn.unPackInt8U();
var applyToWeaponIdx = CommIn.unPackInt8U();
var id = CommIn.unPackInt16U();
itemManager.collectItem(kind, id);
if (playerId == meId) {
me.collectItem(kind, applyToWeaponIdx);
}
break;
case CommCode.die:
var killedId = CommIn.unPackInt8U();
var byId = CommIn.unPackInt8U();
var rs = CommIn.unPackInt8U();
var killedPlayer = players[killedId];
var byPlayer = players[byId];
var byPlayerLastDmg = CommIn.unPackInt8U();
var killedByPlayerLastDmg = CommIn.unPackInt8U();
byPlayer.lastDmgType = byPlayerLastDmg;
killedPlayer.lastDmgType = killedByPlayerLastDmg;
if (killedId == meId && byId != meId) {
SessionStats.updateTerminus(getKeyByValue(CharClass, killedPlayer.charClass), DmgType[killedByPlayerLastDmg].name, "deaths");
} else if (byId == meId && killedId == meId) {
SessionStats.updateTerminus(getKeyByValue(CharClass, killedPlayer.charClass), "Grenade", "deaths", true);
ga("send", "event", "weapon", "deathBy", "Suicide");
}
var killedPlayerName;
if (killedPlayer) {
if (metaGame.scoreKill(byPlayer, killedPlayer)) {
updateTeamUI();
}
killedPlayerName = killedPlayer.name;
var pos = new BABYLON.Vector3(killedPlayer.x_, killedPlayer.y_ + 0.32, killedPlayer.z_);
pAudio.play("shell_burst", pos);
var soundIdx = Math.randomInt(0, 10) + 1;
pAudio.play("death_scream" + soundIdx, pos);
shellFrag(killedPlayer, 100);
yolkSplat(killedPlayer, 100);
shellBurst(killedPlayer, 80, 0.2, 40);
yolkBurst(killedPlayer);
killedPlayer.die();
killedPlayer.actor.mesh_.position.x = killedPlayer.x_;
killedPlayer.actor.mesh_.position.y = killedPlayer.y_;
killedPlayer.actor.mesh_.position.z = killedPlayer.z_;
} else {
killedPlayerName = "N/A";
}
var byPlayerName;
if (byPlayer) {
if (byId === meId) {
if (killedId !== byId) {
SessionStats.streak = byPlayer.bestGameStreak;
SessionStats.updateTerminus(getKeyByValue(CharClass, byPlayer.charClass), DmgType[killedByPlayerLastDmg].name, "kills");
if (DmgType[killedByPlayerLastDmg].name === "Grenade" || DmgType[killedByPlayerLastDmg].name === "Melee") {
ga("send", "event", "weapon", "killedWith", DmgType[killedByPlayerLastDmg].name);
}
}
}
byPlayerName = byPlayer.name;
if (!byPlayer.isDead()) {
byPlayer.scoreKill();
if (byId == meId) {
var el = document.getElementById("bestStreak");
el.innerText = "x" + byPlayer.bestOverallStreak;
}
if (byId == meId) {
kills++;
bestOverallStreak = Math.max(bestOverallStreak, byPlayer.stats.streak);
}
}
} else {
byPlayerName = "N/A";
}
if (killedId != meId) {
if (byId == meId) {
if (killDisplayTimeout) {
clearTimeout(killDisplayTimeout);
}
var killBox = document.getElementById("killBox");
killBox.style.display = "block";
vueApp.killedName = killedPlayerName;
var streakEl = document.getElementById("KILL_STREAK");
if (me.stats.streak > 1) {
streakEl.innerText = me.stats.streak + "-KILL STREAK";
} else {
streakEl.innerText = "";
}
var scale = 1.5;
var scaleInterval = interval.set(function() {
killBox.style.transform = "scale(" + scale + "," + scale + ")";
scale -= 0.05;
if (scale <= 1) {
scale = 1;
interval.clear(scaleInterval);
}
}, 33);
killDisplayTimeout = setTimeout(() => {
if (inGame)
killBox.style.display = "none";
}, 4e3);
}
} else {
gamePaused = true;
camera.parent = null;
camera.position = new BABYLON.Vector3(
viewingPlayer.actor.mesh_.position.x,
viewingPlayer.actor.mesh_.position.y + 0.2,
viewingPlayer.actor.mesh_.position.z
);
if (byPlayer) {
camera.lockedTarget = byPlayer.actor.head;
}
var deathBox = document.getElementById("deathBox");
deathBox.style.display = "block";
vueApp.killName = byPlayerName;
var scale = 2;
var scaleInterval = interval.set(function() {
deathBox.style.transform = "scale(" + scale + "," + scale + ")";
scale -= 0.05;
if (scale <= 1 && inGame) {
interval.clear(scaleInterval);
scale = 1;
}
}, 33);
deaths++;
let rSpawnTimer = adBlocker && !G.productBlockAds && !pokiActive ? 12 : rs - 1;
setRespawnTime(rSpawnTimer);
removeCanvasListeners();
timeout.set(function() {
if (inGame) {
deathBox.style.display = "none";
if (viewingPlayerId == meId) {
openGameMenu();
}
}
}, 3e3);
}
if (byPlayer && killedPlayer) {
addKillText(byPlayer, killedPlayer);
}
rebuildPlayerList();
break;
case CommCode.chat:
var playerId = CommIn.unPackInt8U();
var text = CommIn.unPackString();
addChat(text, playerId);
break;
case CommCode.metaGameState:
metaGame._unPackState(CommIn);
break;
case CommCode.syncMe:
var id = CommIn.unPackInt8U();
var stateIdx = CommIn.unPackInt8U();
var serverStateIdx = CommIn.unPackInt8U();
var x = CommIn.unPackFloat();
var y = CommIn.unPackFloat();
var z = CommIn.unPackFloat();
var climbing = CommIn.unPackInt8U();
var rounds = CommIn.unPackInt8U();
var store = CommIn.unPackInt8U();
var player = players[id];
player.serverStateIdx = serverStateIdx;
var oldx = player.x_;
var oldy = player.y_;
var oldz = player.z_;
var olddx = player.dx;
var olddy = player.dy;
var olddz = player.dz;
var oldYaw = player.yaw_;
var oldPitch = player.pitch_;
var i2 = stateIdx;
var state = player.stateBuffer[i2];
var age = Math.mod(player.stateIdx - stateIdx, stateBufferSize) + FramesBetweenSyncs * 8;
if (player.lastWeaponChange > age) {
if (rounds !== state.rounds || store !== state.store) {
for (var ai = stateIdx; ai != player.stateIdx; ai = Math.mod(ai + 1, stateBufferSize)) {
var aState = player.stateBuffer[ai];
rounds -= aState.shots;
aState.rounds = rounds;
}
player.weapon.ammo.rounds = rounds;
player.weapon.ammo.store = store;
updateAmmoUi();
}
}
if (climbing) {
var dist = Math.length3(state.x_ - x, state.y_ - y, state.z_ - z);
} else {
var dist = Math.length2(state.x_ - x, state.z_ - z);
}
if (controlKeys != 0) {
if (dist < 0.1) {
var corrections = FramesBetweenSyncs * 2;
player.totalCorrections = corrections;
player.corrections = corrections;
player.corrected.dx = x - state.x_;
player.corrected.dy = y - state.y_;
player.corrected.dz = z - state.z_;
break;
}
var corrections = FramesBetweenSyncs * 2;
} else {
if (dist < 0.02)
break;
var corrections = FramesBetweenSyncs * 2;
}
player.totalCorrections = corrections;
player.x_ = x;
player.y_ = y;
player.z_ = z;
player.dx = state.dx;
player.dy = state.dy;
player.dz = state.dz;
player.climbing = state.climbing;
player.jumping = state.jumping;
var oldKeys = me.controlKeys;
for (; i2 != player.stateIdx; i2 = Math.mod(i2 + 1, stateBufferSize)) {
state = player.stateBuffer[i2];
player.controlKeys = state.controlKeys;
player.yaw_ = state.yaw_;
player.update_(true);
}
if (player.climbing) {
var dist = Math.length3(player.x_ - oldx, player.y_ - oldy, player.z_ - oldz);
} else {
var dist = Math.length2(player.x_ - oldx, player.z_ - oldz);
}
if (dist < 0.2) {
player.corrections = corrections;
player.corrected.dx = player.x_ - oldx;
player.corrected.dy = player.y_ - oldy;
player.corrected.dz = player.z_ - oldz;
player.x_ = oldx;
player.y_ = oldy;
player.z_ = oldz;
player.dx = olddx;
player.dy = olddy;
player.dz = olddz;
} else {
player.corrections = 0;
}
player.yaw_ = oldYaw;
player.pitch_ = oldPitch;
player.controlKeys = oldKeys;
break;
case CommCode.syncThem:
var id = CommIn.unPackInt8U();
var x = CommIn.unPackFloat();
var y = CommIn.unPackFloat();
var z = CommIn.unPackFloat();
var climbing = CommIn.unPackInt8U();
var player = players[id];
if (!player || player.id == meId) {
for (var i2 = 0; i2 < FramesBetweenSyncs; i2++) {
CommIn.unPackInt8U();
CommIn.unPackRadU();
CommIn.unPackRad();
}
break;
}
player.stateIdx = 0;
for (var i2 = 0; i2 < FramesBetweenSyncs; i2++) {
player.stateBuffer[i2].controlKeys = CommIn.unPackInt8U();
player.stateBuffer[i2].yaw_ = CommIn.unPackRadU();
player.stateBuffer[i2].pitch_ = CommIn.unPackRad();
}
player.x_ = x;
if (!player.jumping || Math.abs(player.y_ - y) > 0.5)
player.y_ = y;
player.z_ = z;
player.stateBuffer[0].x_ = x;
player.stateBuffer[0].y_ = y;
player.stateBuffer[0].z_ = z;
player.climbing = climbing;
break;
case CommCode.fire:
var id = CommIn.unPackInt8U();
tv1.x = CommIn.unPackFloat();
tv1.y = CommIn.unPackFloat();
tv1.z = CommIn.unPackFloat();
tv2.x = CommIn.unPackFloat();
tv2.y = CommIn.unPackFloat();
tv2.z = CommIn.unPackFloat();
var player = players[id];
if (!player)
break;
if (id != meId) {
player.weapon.actor.fire();
player.weapon.fireMunitions(tv1, tv2);
if (--player.weapon.tracer < 0) {
player.weapon.tracer = player.weapon.constructor.tracer;
}
}
mathSeed = seed;
break;
case CommCode.melee:
var id = CommIn.unPackInt8U();
if (players[id]) {
players[id].meleeCountdown = 17;
players[id].actor.melee();
}
break;
case CommCode.throwGrenade:
var id = CommIn.unPackInt8U();
var x = CommIn.unPackFloat();
var y = CommIn.unPackFloat();
var z = CommIn.unPackFloat();
var dx = CommIn.unPackFloat();
var dy = CommIn.unPackFloat();
var dz = CommIn.unPackFloat();
var player = players[id];
if (!player)
break;
player.grenadeCount--;
if (id != meId) {
player.actor.head.rotation.x = player.pitch_;
player.actor.mesh_.rotation.y = player.yaw_;
} else {
updateAmmoUi();
}
player.actor.throwGrenade();
munitionsManager.throwGrenade(
player,
{ x, y, z },
{ x: dx, y: dy, z: dz }
);
break;
case CommCode.explode:
var itemType = CommIn.unPackInt8U();
var itemId = CommIn.unPackInt16U();
var x = CommIn.unPackFloat();
var y = CommIn.unPackFloat();
var z = CommIn.unPackFloat();
var damage = CommIn.unPackInt8U();
var radius = CommIn.unPackFloat();
let item = null;
if (itemType > 0)
item = G.catalog.findItemById(itemId);
addExplosion(x, y, z, damage, radius, item);
tv1.set(x, y, z);
if (itemType == ItemType2.Grenade) {
pAudio.play(item.item_data.sound || "grenade", tv1);
} else {
pAudio.play("gun_rpegg_rocket_hit", tv1);
}
break;
case CommCode.reload:
var id = CommIn.unPackInt8U();
if (players[id])
players[id].reload();
break;
case CommCode.swapWeapon:
var id = CommIn.unPackInt8U();
var weaponIdx = CommIn.unPackInt8U();
if (players[id])
players[id].swapWeapon(weaponIdx);
break;
case CommCode.hitMe:
var hp = CommIn.unPackInt8U();
var dx = CommIn.unPackFloat();
var dz = CommIn.unPackFloat();
me.hp_ = hp;
me.actor.hit();
hitIndicator.hit(dx, dz);
hitMarkers.hit(dx, dz);
break;
case CommCode.hitMeHardBoiled:
var hb = CommIn.unPackInt8U();
var hp = CommIn.unPackInt8U();
var dx = CommIn.unPackFloat();
var dz = CommIn.unPackFloat();
me.hp_ = hp;
me.hardBoiledValue = hb;
me.actor.hit();
hitIndicator.hit(dx, dz);
hitMarkers.hit(dx, dz);
updateHealthUI();
break;
case CommCode.hitThem:
var id = CommIn.unPackInt8U();
var hp = CommIn.unPackInt8U();
var player = players[id];
if (!player)
break;
player.hp_ = hp;
player.lastDmgType = player.weapon.constructor.id;
player.actor.hit();
if (hp > 0)
yolkSplat(player, Math.clamp(player.hp_ - hp, 0, 100));
break;
case CommCode.respawn:
respawnVideoPlayed = false;
var id = CommIn.unPackInt8U();
var seed = CommIn.unPackInt16U();
var x = CommIn.unPackFloat();
var y = CommIn.unPackFloat();
var z = CommIn.unPackFloat();
var rounds0 = CommIn.unPackInt8U();
var store0 = CommIn.unPackInt8U();
var rounds1 = CommIn.unPackInt8U();
var store1 = CommIn.unPackInt8U();
var grenades = CommIn.unPackInt8U();
var player = players[id];
if (player) {
player.actor.removeFromPlay();
player.randomGen_.setSeed(seed);
player.weapons[0].ammo.rounds = rounds0;
player.weapons[0].ammo.store = store0;
player.weapons[1].ammo.rounds = rounds1;
player.weapons[1].ammo.store = store1;
player.grenades = grenades;
player.respawn(x, y, z);
if (id == meId) {
resumeGame();
resetPlayerUI();
canvas.requestPointerLock({ unadjustedMovement: settings.fastPollMouse });
console.log("CommCode.respawn received from server for this player");
InputQueue.init();
doFirstPersonCamera();
reticle.show();
reticle.showDot();
if (chatting)
chatInEl.focus();
} else {
rebuildPlayerList();
}
}
break;
case CommCode.respawnDenied:
openGameMenu();
break;
case CommCode.changeCharacter:
var id = CommIn.unPackInt8U();
var classIdx = CommIn.unPackInt8U();
var primaryWeaponIdx = CommIn.unPackInt16U();
var secondaryWeaponIdx = CommIn.unPackInt16U();
var shellColor = CommIn.unPackInt8U();
var hatIdx = CommIn.unPackInt16U();
var stampIdx = CommIn.unPackInt16U();
var grenadeIdx = CommIn.unPackInt16U();
var meleeIdx = CommIn.unPackInt16U();
var primaryWeaponItem = G.catalog.findItemById(primaryWeaponIdx);
var secondaryWeaponItem = G.catalog.findItemById(secondaryWeaponIdx);
var hatItem = G.catalog.findItemById(hatIdx);
var stampItem = G.catalog.findItemById(stampIdx);
var grenadeItem = G.catalog.findItemById(grenadeIdx);
var meleeItem = G.catalog.findItemById(meleeIdx);
var player = players[id];
if (player) {
player.changeCharacter(classIdx, primaryWeaponItem, secondaryWeaponItem, shellColor, hatItem, stampItem, grenadeItem, meleeItem);
}
break;
case CommCode.switchTeam:
var id = CommIn.unPackInt8U();
var toTeam = CommIn.unPackInt8U();
var player = players[id];
if (player) {
if (id == meId) {
myTeam = toTeam;
vueApp.setTeam(myTeam);
if (metaGame.teamScore[toTeam] >= metaGame.teamScore[player.team] && metaGame.teamScore[toTeam] > 0) {
player.canTakeTeamBonus = false;
}
}
player.team = toTeam;
player.score = 0;
player.stats.kills = 0;
player.stats.streak = 0;
player.bestGameStreak = 0;
if (!CommIn.isMoreDataAvailable() || CommIn.peekInt8U() !== CommCode.switchTeam) {
updateActorTeams();
rebuildPlayerList();
}
}
break;
case CommCode.switchTeamFail:
vueApp.showGenericPopup("ui_game_fairteams_header", "ui_game_fairteams_text", "ok");
break;
case CommCode.ping:
ping = Date.now() - pingStartTime;
pingTotal += ping;
pingSamples++;
var el = document.getElementById("ping");
if (ping < 100)
el.style.color = "#0f0";
else if (ping < 150)
el.style.color = "#ff0";
else if (ping < 200)
el.style.color = "#f90";
else
el.style.color = "#f00";
el.innerText = ping + "ms";
setTimeout(function() {
if (ws) {
var out2 = CommOut.getBuffer();
out2.packInt8(CommCode.ping);
out2.send(ws);
pingStartTime = Date.now();
}
}, 1e3);
break;
case CommCode.gameLocked:
notify(vueApp.loc["ui_game_locked"], 1e4);
break;
case CommCode.updateBalance:
var newBalance = CommIn.unPackInt32U();
console.log("updating balance from server: " + newBalance);
G.playerAccount.currentBalance = newBalance;
break;
case CommCode.expireUpgrade:
console.log("upgrade has expired");
checkUpgrade();
break;
case CommCode.beginShellStreak:
var id = CommIn.unPackInt8U();
var ksType = CommIn.unPackInt8U();
var player = players[id];
player.beginShellStreak(ksType);
break;
case CommCode.endShellStreak:
var id = CommIn.unPackInt8U();
var ksType = CommIn.unPackInt8U();
var player = players[id];
player.endShellStreak(ksType);
break;
case CommCode.gameOptions:
GameOptions.parse();
vueData.selectedWeaponDisabled = GameOptions.isSelectedWeaponDisabled(G.playerAccount.classIdx);
vueApp.$refs.gameScreen.$forceUpdate();
vueApp.$refs.gameScreen.$refs.weaponSelect.$forceUpdate();
break;
case CommCode.gameAction:
let action = CommIn.unPackInt8U();
switch (action) {
case GameActions.reset:
metaGame.reset();
var el = document.getElementById("gameMessage");
el.innerHTML = getLocText("ingame_reset");
el.className = "show";
setTimeout(() => {
el.className = "hide";
}, 3e3);
break;
case GameActions.pause:
if (me.playing) {
openGameMenu();
}
break;
}
break;
default:
console.log("CommCode error: " + cmd2 + "/" + String.fromCharCode(cmd2) + " - previous cmd: " + JSON.stringify(prevCmd));
break;
}
prevCmd.push(cmd2);
if (prevCmd.length > 4)
prevCmd.shift();
}
};
ws.onclose = (e2) => {
handleCloseCode(e2.code);
};
}
function resetPlayerUI() {
reticle.hide();
reticle.hideDot();
scope.hide();
reticle.setPowerful(false);
camera.fov = 1.25;
grenadePowerUp = false;
document.getElementById("grenadeThrowContainer").style.visibility = "hidden";
document.getElementById("eggBreakerContainer").className = "off";
}
function showShellStreakMessage(msg) {
var el = document.getElementById("shellStreakMessage");
el.innerText = msg;
el.className = "appear";
var el = document.getElementById("shellStreakCaption");
el.innerText = "x" + me.stats.streak + " Shellstreak";
el.style.visibility = "visible";
setTimeout(() => {
document.getElementById("shellStreakMessage").className = "disappear";
var el2 = document.getElementById("shellStreakCaption");
el2.style.visibility = "hidden";
}, 3e3);
}
function updateActorTeams() {
for (var i2 = 0; i2 < playerLimit; i2++) {
var player = players[i2];
if (player && player.actor) {
player.actor.updateTeam();
}
}
}
var rotInc = Math.PI / 2;
async function loadMap(idx, callback) {
console.log("loadMap()");
Collider.init(gameScene);
if (playOffline) {
minMap = JSON.parse(localStore.getItem("mapBackup"));
} else {
var name = maps[idx].filename;
var response = await fetch("maps/" + name + ".json?" + maps[idx].hash);
minMap = await response.json();
console.log("MAP: " + name);
vueApp.setGameDataUi(minMap.name);
}
vueApp.showSpinner("building_map", "ui_game_waitforit", true);
if (minMap.sun) {
gameScene.sunLight = {
direction: new BABYLON.Vector3(minMap.sun.direction.x, minMap.sun.direction.y, minMap.sun.direction.z),
diffuse: BABYLON.Color3.FromHexString(minMap.sun.color)
};
} else {
gameScene.sunLight = {
direction: new BABYLON.Vector3(0.2, 1, 0.1),
diffuse: new BABYLON.Color3.White()
};
}
if (minMap.ambient) {
gameScene.ambientColor = BABYLON.Color3.FromHexString(minMap.ambient);
} else {
gameScene.ambientColor = new BABYLON.Color3(0.2, 0.2, 0.2);
}
if (minMap.fog) {
console.log("FOG:", minMap.fog);
if (minMap.fog.density > 0) {
gameScene.fogMode = BABYLON.Scene.FOGMODE_EXP2;
gameScene.fogColor = BABYLON.Color3.FromHexString(minMap.fog.color);
gameScene.fogDensity = minMap.fog.density;
gameScene.fogEnabled = true;
} else {
gameScene.fogEnabled = false;
gameScene.fogDensity = 0;
}
} else {
gameScene.fogMode = BABYLON.Scene.FOGMODE_EXP2;
gameScene.fogColor = new BABYLON.Color4(0.5, 0.55, 0.6, 1);
gameScene.fogDensity = 0.01;
}
minMap.extents.x.min = 0;
minMap.extents.y.min = 0;
minMap.extents.z.min = 0;
var meshIndex = buildMapData(minMap, function(str) {
alert("The following map meshes were not found:\n\n" + str + "\nTry clearing your cache and reload the page!");
});
MapTools.createMapCells(gameScene, meshIndex, minMap, null, null, (mesh2, particles) => {
vueApp.showSpinner("building_map", "ui_game_lights");
mapMesh = MapTools.stripTris(map.data, mapMeshes, mesh2, particles);
mapMesh.position.set(0.5, 0.5, 0.5);
mapMesh.receiveShadows = true;
complete();
});
capZoneMeshes = [];
if (gameType == GameType.king) {
for (var zone = 1; zone <= numCaptureZones; zone++) {
MapTools.createMapCells(gameScene, meshIndex, minMap, "DYNAMIC.capture-zone.none", zone, (mesh2, particles) => {
if (mesh2) {
let v = new BABYLON.Vector3();
for (let p of particles) {
v.x += p.x;
v.y += p.y;
v.z += p.z;
}
v.scaleInPlace(1 / particles.length);
v.x += 0.5;
v.y += 0.6;
v.z += 0.5;
mesh2.capIconPosition = v;
mesh2.position.set(0.5, 0.5, 0.5);
mesh2.material = gameScene.getMaterialByName("colorized");
capZoneMeshes.push(mesh2);
}
});
}
}
async function complete() {
var lightmapMin;
if (playOffline) {
lightmapMin = localStorage.getItem("lightmap");
lightmapMin = JSON.parse(lightmapMin);
} else {
lightmapMin = await fetchLightmap("maps/" + name + ".lightmap?" + maps[idx].hash, (part, total) => {
vueApp.showSpinnerLoadProgress(Math.ceil(part / total * 100));
});
}
if (lightmapMin) {
var lightmap2 = mapMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
for (var i2 = 0, j = 0; i2 < lightmapMin.length; i2 += 3, j += 4) {
lightmap2[j] = lightmapMin[i2] / 255;
lightmap2[j + 1] = lightmapMin[i2 + 1] / 255;
lightmap2[j + 2] = lightmapMin[i2 + 2] / 255;
}
mapMesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, lightmap2);
}
mapMesh.material = gameScene.getMaterialByName("map");
mapMesh.freezeWorldMatrix();
if (!noSkybox) {
var skyboxName = minMap.skybox || "default";
var skybox = BABYLON.MeshBuilder.CreateBox("skyBox", { size: 100 }, gameScene);
skybox.infiniteDistance = true;
var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", gameScene);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.fogEnabled = false;
skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("img/skyboxes/" + skyboxName + "/skybox", gameScene);
skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
skybox.material = skyboxMaterial;
}
let endOfLoadDate = Date.now();
let endOfLoadTime = endOfLoadDate - setNewTimerStart;
if (endOfLoadTime > 3e3) {
nowComplete();
} else {
setTimeout(() => nowComplete(), 3e3 - endOfLoadTime);
}
}
;
function nowComplete() {
console.log("Now complete");
if (playOffline)
Loader2.hide();
setTimeout(() => {
vueApp.hideSpinner();
}, 600);
vueApp.hideLoadingScreenAd();
ga("send", "timing", "load", "mapLoaded", Math.round(performance.now()) - Math.round(timerPlayStart), minMap.name);
callback();
}
}
async function fetchLightmap(url, onprogress) {
var response = await fetch(url);
var reader = response.body.getReader();
var contentLength = +response.headers.get("Content-Length");
var receivedLength = 0;
var chunks = [];
while (true) {
var { done, value } = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
if (onprogress) {
onprogress(receivedLength, contentLength);
}
}
var chunksAll = new Uint8Array(receivedLength);
var position = 0;
for (var chunk of chunks) {
chunksAll.set(chunk, position);
position += chunk.length;
}
lightmap = new Uint8Array(chunksAll);
return lightmap;
}
function updateLogic() {
var currentTimeStamp = performance.now();
now = currentTimeStamp;
if (roundEnded)
return;
if (pingSamples > 10) {
highestPing = Math.max(highestPing, ping);
}
var step = 1e3 / 30;
var delta = 2;
InputQueue.update();
while (lastTimeStamp < currentTimeStamp) {
lastTimeStamp += step;
if (!freezeFrame) {
for (var i2 = 0; i2 < playerLimit; i2++) {
var player = players[i2];
if (player) {
if (player.id === meId) {
player.chatLines = Math.max(0, player.chatLines - 1 / (30 * 4));
if (player.chatLines <= 2) {
chatInEl.style.visibility = "visible";
}
}
if (player.playing) {
player.actor.updateLerp();
player.update_();
}
}
}
if (spatula)
spatula.update();
} else {
me.actor.updateLerp();
me.update_();
}
if (me) {
if (me.weapon && me.weapon.ammo.rounds == 0) {
if (me.stateIdx % 20 == 0) {
document.getElementById("ammo").style.color = "#f00";
} else if (me.stateIdx % 20 == 10) {
document.getElementById("ammo").style.color = "#fff";
}
}
if (grenadePowerUp == true) {
grenadeThrowPower = Math.min(grenadeThrowPower + 0.03, 1);
if (grenadeThrowPower > 0) {
document.getElementById("grenadeThrowContainer").style.visibility = "visible";
document.getElementById("grenadeThrow").style.height = grenadeThrowPower * 100 + "%";
}
}
}
if (!freezeFrame) {
munitionsManager.updateLogic();
}
metaGame.update();
}
var mat = BABYLON.Matrix.Invert(camera.getViewMatrix());
cameraDirection.copyFrom(BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat));
cameraDirection.normalize();
BAWK.update();
metaGameUI.update();
}
var deltaStart = performance.now();
function updateActors() {
var deltaNow = performance.now();
var delta = Math.min((deltaNow - deltaStart) / (1e3 / 60), 8);
deltaStart = deltaNow;
if (fpsTotal >= 0) {
var fps = G.engine.getFps();
fpsTotal += fps;
fpsSamples++;
}
if (fpsSamples % 10 == 0) {
fpsAverage = fpsTotal / fpsSamples;
var fpsEl = document.getElementById("FPS");
fpsEl.innerText = Math.floor(fps + 0.5);
if (viewingPlayer && !(viewingPlayer.activeShellStreaks & ShellStreak.HardBoiled)) {
updateHealthUI();
}
}
if (pingSamples > 10) {
highestPing = Math.max(highestPing, ping);
}
if (!freezeFrame) {
for (var i2 = 0; i2 < playerLimit; i2++) {
var player = players[i2];
if (player) {
if (player.playing) {
player.actor.handsToWeaponSkeleton();
if (player.actor) {
player.actor.update(delta);
}
}
}
}
if (spatula)
spatula.actor.update(delta);
} else {
me.actor.update(delta);
}
if (me) {
hitIndicator.update(delta);
reticle.update(delta);
hitMarkers.update(delta, me.yaw_);
}
if (!freezeFrame) {
munitionsManager.updateActors(delta);
itemManager.update(delta);
updateParticles(explosionSmokeManager, delta);
updateParticles(explosionFireManager, delta);
updateParticles(shellFragManager, delta);
updateParticles(shellBurstManager, delta);
updateParticles(yolkManager, delta);
updateParticles(yolkSplatManager, delta);
}
if (mapOverview) {
mapOverviewAxis += 2e-3 * delta;
camera.position.x = Math.sin(mapOverviewAxis) * map.height + map.width / 2;
camera.position.z = Math.cos(mapOverviewAxis) * map.height + map.depth / 2;
camera.setTarget(new BABYLON.Vector3(map.width / 2, map.height / 4, map.depth / 2));
}
if (spectate) {
spectator.update(delta);
}
}
function hitPlayer(playerHit, byMunition, dmg, hx, hz) {
dmg *= GameOptions.value.damage;
let byPlayer = byMunition.player_;
byPlayer.lastDamageGivenType = byMunition.dmgTypeId;
playerHit.lastDamageTakenType = byMunition.dmgTypeId;
if (!playerHit.playing || playerHit.shield > 0)
return;
var hp = Math.max(0, Math.floor(playerHit.hp_ - dmg));
if (hp > 0)
shellFrag(playerHit, Math.clamp(dmg, 0, 100));
}
function updateHealthUI() {
if (viewingPlayer.activeShellStreaks & ShellStreak.HardBoiled) {
var el = document.getElementById("hardBoiledContainer");
if (el.style.visibility != "visible") {
el.style.visibility = "visible";
document.getElementById("healthContainer").style.visibility = "hidden";
}
var val = Math.floor(viewingPlayer.hardBoiledValue);
document.getElementById("hardBoiledValue").innerText = val;
var el = document.getElementById("hardBoiledShieldFill");
el.style.clipPath = "inset(" + (100 - val) + "% 0 0 0)";
} else {
var el = document.getElementById("healthContainer");
if (el.style.visibility != "visible") {
el.style.visibility = "visible";
document.getElementById("hardBoiledContainer").style.visibility = "hidden";
}
var barEl = document.getElementById("healthBar");
var hpEl = document.getElementById("healthHp");
var r = 2.3 - viewingPlayer.hp_ / 43.478;
barEl.setAttribute("stroke-dashoffset", r * 6.2832 + "em");
var val = Math.floor(viewingPlayer.hp_);
hpEl.innerText = val;
}
}
var pingStartTime;
function serverSync() {
if (me) {
var out = CommOut.getBuffer();
out.packInt8(CommCode.syncMe);
out.packInt8(Math.mod(me.stateIdx - FramesBetweenSyncs, stateBufferSize));
out.packInt8(me.serverStateIdx);
var startIdx = Math.mod(me.stateIdx - FramesBetweenSyncs, stateBufferSize);
for (var i2 = 0; i2 < FramesBetweenSyncs; i2++) {
var idx = Math.mod(startIdx + i2, stateBufferSize);
out.packInt8(me.stateBuffer[idx].controlKeys);
out.packInt8(me.stateBuffer[idx].shots);
out.packRadU(me.stateBuffer[idx].yaw_);
out.packRad(me.stateBuffer[idx].pitch_);
me.stateBuffer[Math.mod(idx - stateBufferSize / 2, stateBufferSize)].shots = 0;
}
out.send(ws);
}
}
function switchTeam() {
if (gamePaused) {
console.log("Team switch requested");
var out = CommOut.getBuffer();
out.packInt8(CommCode.switchTeam);
out.send(ws);
}
}
function refreshGameState() {
if (!inGame)
return;
metaGame.suppressSound = true;
var out = CommOut.getBuffer();
out.packInt8(CommCode.refreshGameState);
out.send(ws);
}
function addPlayer(playerData) {
if (playerData.id_ == meId)
viewingPlayerId = playerData.id_;
var player = new Player(playerData, gameScene);
if (player.id == meId) {
me = player;
viewingPlayer = player;
me.ws = ws;
updateAmmoUi();
} else {
let i2 = playerHistory.findIndex((p) => p.uniqueId === playerData.uniqueId_);
if (i2 >= 0) {
playerHistory.splice(i2, 1);
}
playerHistory.push({
id: playerData.id_,
uniqueId: playerData.uniqueId_,
name: playerData.name_,
muted: playerData.muted_,
isGameOwner: playerData.isGameOwner_
});
if (playerHistory.length > 50) {
playerHistory.shift();
}
}
if (!player.playing)
player.actor.removeFromPlay();
players[playerData.id_] = player;
rebuildPlayerList();
}
function removePlayer(playerId) {
var player = players[playerId];
if (playerId == meId) {
console.log("Tried to remove ME");
return;
}
if (player) {
player.actor.remove();
if (viewingPlayerId === playerId) {
spectator.unlock();
}
delete players[playerId];
rebuildPlayerList();
}
}
function getPlayerSocial(social) {
if (social) {
try {
const PLAYERSOCIAL = JSON.parse(social);
if (PLAYERSOCIAL.length > 0 && hasValue(PLAYERSOCIAL[0])) {
return PLAYERSOCIAL.find((item) => item.active);
}
} catch (error) {
}
return false;
}
return false;
}
function showPlayerIcon(player) {
if (player.hideBadge) {
return false;
}
return player.upgradeProductId && player.upgradeProductId > 0 || player.social.length > 2 && player.social.includes('"active": true');
}
function findPlayerByUniqueId(uniqueId) {
for (let i2 = 0; i2 < playerLimit; i2++) {
if (players[i2] && players[i2].uniqueId === uniqueId) {
return players[i2];
}
}
return playerHistory.find((p) => p.uniqueId === uniqueId);
}
function playerActionData(uniqueId, social, vip) {
let player = findPlayerByUniqueId(uniqueId);
if (player) {
return function() {
var data2 = {
uniqueId,
isGameOwner: player.isGameOwner,
muted: player.muted,
playerName: player.name,
muteFunc: function() {
mutePlayer(uniqueId);
},
bootFunc: function() {
bootPlayer(uniqueId);
},
banFunc: function(reason, duration) {
banPlayer(uniqueId, reason, duration);
},
infoFunc: function() {
getPlayerInfo(uniqueId);
},
reportFunc: function(reasons) {
reportPlayer(uniqueId, reasons);
},
social,
vipMember: vip
};
vueApp.showPlayerActionsPopup(data2);
};
}
}
function rebuildPlayerList() {
playerCount[0] = 0;
playerCount[1] = 0;
playerCount[2] = 0;
var playerIdxs = [];
for (var i2 = 0; i2 < playerLimit; i2++) {
if (players[i2]) {
playerIdxs.push(i2);
playerCount[players[i2].team]++;
}
}
metaGameUI.sortPlayerList(playerIdxs);
var list = document.getElementById("playerList").children;
var i2;
for (i2 = 0; i2 < playerIdxs.length; i2++) {
var player = players[playerIdxs[i2]];
var slot = list[i2];
var nameAndScore = slot.children[0];
var name = nameAndScore.children[0];
var score = nameAndScore.children[1];
var icons = slot.children[1];
name.classList.add("playerSlot--name");
score.classList.add("playerSlot--score");
icons.classList.add("playerSlot--icons");
slot.style.display = "block";
slot.style.opacity = 1;
name.innerText = player.name;
if (player.id != meId) {
const GETSOCIALMEDIA2 = !player.hideBadge ? getPlayerSocial(player.social) : false;
const ISVIP = player.upgradeProductId && player.upgradeProductId > 0 && !player.hideBadge;
slot.onclick = playerActionData(player.uniqueId, GETSOCIALMEDIA2, ISVIP);
slot.style.pointerEvents = "all";
slot.style.cursor = "pointer";
if (!player.playing) {
slot.style.opacity = 0.3;
}
}
score.innerText = player.score;
nameAndScore.classList.add("playerSlot--name-score");
let nameAndScoreClass = "playerSlot--name-score", isMeClass = "playerSlot-player-is-me", isThemClass = "playerSlot-player-is-them";
let spectateClass = "";
if (spectate && spectateMode === Spectate.firstPerson && player.id === spectator.playerIdx) {
spectateClass = "playerSlot-spectating";
}
if (player.id == meId) {
nameAndScore.className = `${nameAndScoreClass} ${isMeClass} ${teamColors.meClass[player.team]}`;
} else {
nameAndScore.className = `${spectateClass} ${nameAndScoreClass} ${isThemClass} ${teamColors.themClass[player.team]}`;
}
icons.innerText = "";
const iconEgg = document.createElement("i"), iconMute = document.createElement("i"), iconWatch = document.createElement("i");
iconEgg.className = "fas fa-egg hidden text_gold vip-egg";
const GETSOCIALMEDIA = getPlayerSocial(player.social);
if (GETSOCIALMEDIA) {
iconEgg.className = `fab ${SOCIALMEDIA[GETSOCIALMEDIA.id]} hidden`;
}
iconMute.className = "fas fa-ban hidden";
if (showPlayerIcon(player))
iconEgg.classList.remove("hidden");
if (player.muted)
iconMute.classList.remove("hidden");
iconWatch.className = "fas fa-exclamation-triangle red hidden";
if (watchPlayer === player.uniqueId)
iconWatch.classList.remove("hidden");
icons.appendChild(iconEgg);
icons.appendChild(iconMute);
icons.appendChild(iconWatch);
}
;
while (i2 < playerLimit) {
list[i2].style.display = "none";
i2++;
}
}
function bootPlayer(uniqueId) {
var out = CommOut.getBuffer();
out.packInt8(CommCode.bootPlayer);
out.packString(uniqueId);
out.send(ws);
}
function banPlayer(uniqueId, reason, duration) {
var out = CommOut.getBuffer();
out.packInt8(CommCode.banPlayer);
out.packString(uniqueId);
out.packString(reason);
out.packInt8(duration);
out.send(ws);
}
function mutePlayer(uniqueId) {
for (let i2 = 0; i2 < playerLimit; i2++) {
var player = players[i2];
if (player && player.id !== meId && player.uniqueId === uniqueId) {
if (player.muted) {
player.muted = false;
if (!settings.safeNames)
player.name = player.normalName;
} else {
player.muted = true;
if (!settings.safeNames)
player.name = player.safeName;
}
player.actor.setupNameSprite();
rebuildPlayerList();
break;
}
}
var player = playerHistory.find((p) => p.id !== meId && p.uniqueId === uniqueId);
if (player)
player.muted = !player.muted;
}
function reportPlayer(uniqueId, reasons) {
var out = CommOut.getBuffer();
out.packInt8(CommCode.reportPlayer);
out.packString(uniqueId);
out.packInt8(reasons);
out.send(ws);
vueApp.showGenericPopup("report_confirm_title", "report_confirm_message", "ok");
}
function getPlayerInfo(uniqueId) {
let player = findPlayerByUniqueId(uniqueId);
if (!player)
return;
let bc = new BroadcastChannel("ShellShockersAdmin");
bc.postMessage({ cmd: "getPlayer", id: player.dbId, ip: player.ip });
bc.close();
}
function updateAmmoUi() {
if (!me)
return;
var el = document.getElementById("weaponName");
el.innerHTML = me.weapon.constructor.weaponName;
el = document.getElementById("ammo");
el.style.color = "#fff";
var ammo = me.weapon.ammo;
var rounds = Math.max(Math.min(ammo.rounds, ammo.capacity), 0);
var store = Math.max(Math.min(ammo.store, ammo.storeMax), 0);
el.innerHTML = rounds + "/" + store;
for (var i2 = 1; i2 <= 3; i2++) {
if (me.grenadeCount >= i2) {
document.getElementById("grenade" + i2).src = "img/ico_grenade.png?v=1";
} else {
document.getElementById("grenade" + i2).src = "img/ico_grenadeEmpty.png?v=1";
}
}
}
var lastKey = null;
function captureKeys() {
lastKey = null;
document.addEventListener("keydown", onKeyDown);
document.addEventListener("keyup", onKeyUp);
}
function releaseKeys() {
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener("keyup", onKeyUp);
}
function mapControl(source, code) {
var control;
if (spectate) {
control = inputToControlMap[source].spectate[code];
if (!control) {
control = inputToControlMap[source].game[code];
}
if (spectateMode === Spectate.firstPerson) {
if (code === "ARROWUP")
control = "up";
if (code === "ARROWDOWN")
control = "down";
}
} else {
var control = inputToControlMap[source].game[code];
}
return control;
}
function inputDown(source, code) {
if (!spectate && (!document.pointerLockElement || !me.playing))
return;
var control = mapControl(source, code);
handleInputDown(control);
}
function handleInputDown(control) {
switch (control) {
case "up":
case "down":
case "left":
case "right":
case "jump":
case "ascend":
case "descend":
var bit = CONTROL[control];
controlKeys |= bit;
break;
case "inspect":
if (document.pointerLockElement && me) {
me.actor.inspect();
}
break;
case "melee":
if (document.pointerLockElement && me) {
InputQueue.add(InputQueue.melee);
}
var bit = CONTROL[control];
controlKeys |= bit;
break;
case "fire":
if (document.pointerLockElement && me) {
InputQueue.add(InputQueue.fire);
}
var bit = CONTROL[control];
controlKeys |= bit;
break;
case "grenade":
if (document.pointerLockElement && me && !grenadePowerUp && me.canSwapOrReload() && me.grenadeCount > 0) {
grenadePowerUp = true;
grenadeThrowPower = -0.15;
}
break;
case "scope":
var bit = CONTROL[control];
if (settings.holdToAim) {
controlKeys |= bit;
} else {
if (me.scope) {
controlKeys ^= controlKeys & bit;
} else {
controlKeys |= bit;
}
}
break;
case "reload":
InputQueue.add(InputQueue.reload);
break;
case "swap_weapon":
InputQueue.add(InputQueue.swap);
break;
case "toggle_freecam":
if (spectate) {
if (spectateMode === Spectate.freeCamera) {
spectateMode = Spectate.firstPerson;
spectator.firstPerson();
} else {
spectateMode = Spectate.freeCamera;
spectator.freeCamera();
}
}
break;
}
}
function inputUp(source, code) {
if (!spectate && (!document.pointerLockElement || !me.playing))
return;
var control = mapControl(source, code);
handleInputUp(control);
}
function handleInputUp(control) {
switch (control) {
case "fire":
var bit = CONTROL[control];
controlKeys ^= controlKeys & bit;
break;
case "scope":
if (settings.holdToAim) {
me.scopeOut();
var bit = CONTROL[control];
controlKeys ^= controlKeys & bit;
}
break;
case "grenade":
if (document.pointerLockElement && grenadePowerUp && me) {
document.getElementById("grenadeThrowContainer").style.visibility = "hidden";
grenadePowerUp = false;
me.throwGrenade(grenadeThrowPower);
}
break;
case "up":
if (spectate && spectateMode === Spectate.firstPerson) {
spectator.spectateNextPlayer(-1);
controlKeys = 0;
break;
}
case "down":
if (spectate && spectateMode === Spectate.firstPerson) {
spectator.spectateNextPlayer(1);
controlKeys = 0;
break;
}
case "left":
case "right":
case "jump":
case "melee":
case "ascend":
case "descend":
var bit = CONTROL[control];
controlKeys ^= controlKeys & bit;
break;
}
}
var debugWindow;
function debugDump() {
if (!debugWindow) {
debugWindow = window.open("", "", "name=Debug");
debugWindow.document.write("");
return;
}
for (var i2 = 0; i2 < playerLimit; i2++) {
var p = players[i2];
if (p) {
var player = {
name: p.name,
hp: p.hp_,
playing: p.playing,
posX: p.x_,
posY: p.y_,
posZ: p.z_,
actorX: p.actor.mesh_.position.x,
actorY: p.actor.mesh_.position.y,
actorZ: p.actor.mesh_.position.z,
transformEnabled: p.actor.mesh_.isEnabled(),
transformVisible: p.actor.mesh_.isVisible,
transformFrozen: p.actor.mesh_.isWorldMatrixFrozen,
shellEnabled: p.actor.bodyMesh_.isEnabled(),
shellVisible: p.actor.bodyMesh_.isVisible,
shellFrozen: p.actor.bodyMesh_.isWorldMatrixFrozen,
weaponEnabled: p.weapon.actor.gunMesh_.isEnabled(),
weaponVisible: p.weapon.actor.gunMesh_.isVisible
};
debugWindow.document.write(JSON.stringify(player) + "\n");
}
}
debugWindow.document.write("
");
}
function addKillText(byPlayer, killedPlayer) {
var msgs = [
` ${getLocText("ingame_kill_text_scrambled")} `,
` ${getLocText("ingame_kill_text_beat")} `,
` ${getLocText("ingame_kill_text_poached")} `,
` ${getLocText("ingame_kill_text_whipped")} `,
` ${getLocText("ingame_kill_text_fried")} `,
` ${getLocText("ingame_kill_text_cracked")} `
];
var str = '' + byPlayer.name + "" + msgs[Math.randomInt(0, msgs.length)] + '' + killedPlayer.name + "";
var count = (killEl.innerHTML.match(/
/g) || []).length;
if (count > 4) {
killEl.innerHTML = killEl.innerHTML.substr(killEl.innerHTML.search("
") + 4);
}
killEl.innerHTML += str + "
";
}
function canChat() {
if (isPrivateGame || G.playerAccount.isEmailVerified || G.playerAccount.accountAge > 1e3 * 60 * 60 * 12) {
return true;
}
return false;
}
function initChatIn() {
canvas.focus();
chatInEl.style.display = "block";
if (!canChat()) {
chatInEl.value = getLocText("ingame_sign_in_to_chat");
chatInEl.style.pointerEvents = "none";
} else {
chatInEl.value = getLocText("ingame_press_enter_to_chat");
chatInEl.style.pointerEvents = "auto";
}
chatInEl.style.background = "transparent";
chatInEl.blur();
chatting = false;
}
function addChat(str, fromPlayerIdx, clickFnc, icon) {
const chatEl = document.createElement("div"), chatStr = document.createElement("span"), chatPlayer = document.createElement("div"), chatName = document.createElement("span"), chatIcon = document.createElement("i");
let isVip = false;
let getSocialMedia = false;
let uniqueId = false;
chatEl.classList.add("chat-item");
chatPlayer.style.display = "inline-block";
if (fromPlayerIdx > 253) {
if (fromPlayerIdx === 255) {
chatName.textContent = "SERVER: ";
chatPlayer.style.color = "#ff0";
} else if (fromPlayerIdx === 254) {
chatName.textContent = "MOD: ";
chatPlayer.style.color = "#0f0";
}
chatName.classList.add("chat-player-name", "ss_marginright_xs");
chatPlayer.appendChild(chatName);
} else {
let fromPlayer = players[fromPlayerIdx];
chatParser.innerHTML = str;
str = chatParser.textContent.trim();
if (fromPlayerIdx === meId || fromPlayerIdx !== null && fromPlayer && !fromPlayer.muted && str.length > 0 && !isBadWord(str) && str.indexOf("<") < 0) {
isVip = fromPlayer.upgradeProductId && fromPlayer.upgradeProductId > 0 ? true : false, getSocialMedia = getPlayerSocial(fromPlayer.social);
if (getSocialMedia && !fromPlayer.hideBadge) {
chatIcon.classList.add("fab", SOCIALMEDIA[getSocialMedia.id]);
chatIcon.classList.add("ss_marginright_xs");
} else if (isVip && !fromPlayer.hideBadge) {
chatIcon.classList.add("fas", "fa-egg", "hidden", "text_gold", "vip-egg");
chatIcon.classList.add("ss_marginright_xs");
}
uniqueId = fromPlayer.uniqueId;
chatName.classList.add("chat-player-name", "ss_marginright_xs");
chatName.textContent = fromPlayer.name + ": ";
chatPlayer.style.color = teamColors.text[fromPlayer.team];
chatPlayer.appendChild(chatIcon);
chatPlayer.appendChild(chatName);
} else if (fromPlayerIdx !== null) {
return;
}
}
const chatItems = chatOutEl.querySelectorAll(".chat-item");
if (chatItems.length > 4) {
chatItems[0].remove();
}
if (icon) {
str = str.format(icon);
}
chatStr.innerHTML = str;
chatEl.appendChild(chatPlayer);
chatEl.appendChild(chatStr);
chatEl.classList.add("clickme");
chatEl.onclick = () => {
if (!uniqueId && clickFnc) {
clickFnc();
} else {
if (uniqueId != me.uniqueId) {
chatName.classList.add("clickme");
playerActionData(uniqueId, getSocialMedia, isVip)();
}
}
};
chatOutEl.appendChild(chatEl);
if (chatContainer)
chatContainer.scrollTop = chatContainer.scrollHeight;
}
function sendChat(text) {
var out = CommOut.getBuffer();
out.packInt8(CommCode.chat);
out.packString(text);
out.send(ws);
}
function onChatKeyDown(e2) {
e2 = e2 || window.event;
var key = e2.key;
chatInEl.value = fixStringWidth(chatInEl.value, 280);
switch (key) {
case "Enter":
var text = chatInEl.value.trim();
if (text != "" && text.indexOf("<") < 0) {
sendChat(text);
if (!observingGame)
addChat(text, meId);
if (!G.adminRoles && !isGameOwner) {
me.chatLines++;
if (me.chatLines > 2) {
chatInEl.style.visibility = "hidden";
}
}
chatEvents++;
if (chatEvents === 1) {
ga("send", "event", "game", "stats", "chat", chatEvents);
}
}
case "Tab":
e2.preventDefault();
e2.stopPropagation();
stopChat();
break;
}
}
function startChat() {
if (me.chatLines <= 2 && canChat()) {
releaseKeys();
chatInEl.style.background = "rgba(0, 0, 0, 0.5)";
chatInEl.value = "";
chatInEl.focus();
lastKey = null;
chatting = true;
}
}
function stopChat() {
initChatIn();
captureKeys();
}
function onKeyDown(e2) {
e2 = e2 || window.event;
var key = e2.key;
if (key == lastKey)
return;
lastKey = key;
if (!grenadePowerUp && controlKeys == 0 && key == "Enter" && settings.enableChat) {
startChat();
return;
}
if (!chatting) {
if (key == "Tab") {
k = "ESCAPE";
e2.preventDefault();
pausePlayerGame("down");
}
}
var k = ("" + key).toLocaleUpperCase();
if (k == " ") {
k = "SPACE";
e2.preventDefault();
}
if (debug) {
if (k == "`") {
debugDump();
return;
}
if (k == "\\") {
freezeFrame = true;
for (var i2 = 0; i2 < gameScene.particleSystems.length; i2++) {
gameScene.particlesPaused = true;
}
for (var i2 = 0; i2 < playerLimit; i2++) {
if (players[i2] && players[i2].actor) {
players[i2].actor.mesh_.setVisible(true);
players[i2].actor.showNameSprite();
players[i2].actor.positionNameSprite();
}
}
ws.close();
}
}
inputDown("keyboard", k);
}
function onKeyUp(e2) {
e2 = e2 || window.event;
var key = e2.key;
if (key == lastKey)
lastKey = null;
var k = ("" + key).toLocaleUpperCase();
if (k == " ") {
k = "SPACE";
e2.preventDefault();
}
inputUp("keyboard", k);
}
function Scope() {
this.crosshairs = new BABYLON.AbstractMesh("", gameScene);
this.crosshairs.setEnabled(false);
this.crosshairs.position.z = 2;
var p = [
new BABYLON.Vector3(-1, 0, 0),
new BABYLON.Vector3(1, 0, 0)
];
var l = BABYLON.MeshBuilder.CreateLines("", { points: p }, gameScene);
l.layerMask = 536870912;
l.color = BABYLON.Color3.Black();
l.parent = this.crosshairs;
p = [
new BABYLON.Vector3(0, -1, 0),
new BABYLON.Vector3(0, 1, 0)
];
l = BABYLON.MeshBuilder.CreateLines("", { points: p }, gameScene);
l.layerMask = 536870912;
l.color = BABYLON.Color3.Black();
l.parent = this.crosshairs;
}
Scope.prototype.show = function() {
var h = G.engine.getRenderHeight();
this.crosshairs.scaling.x = h / 2;
this.crosshairs.scaling.y = h / 2;
this.crosshairs.setEnabled(true);
document.getElementById("scopeBorder").style.display = "flex";
camera.viewport.width = h / G.engine.getRenderWidth();
camera.viewport.x = 0.5 - camera.viewport.width * 0.5;
};
Scope.prototype.hide = function() {
this.crosshairs.setEnabled(false);
document.getElementById("scopeBorder").style.display = "none";
camera.viewport.width = 1;
camera.viewport.x = 0;
};
function HitIndicator() {
this.mesh_ = new BABYLON.Mesh("hitIndicator", gameScene);
this.mesh_.updatable = true;
this.mesh_.hasVertexAlpha = true;
this.positions = [
0,
0,
0,
// 0 Center
0,
0.5,
0,
// 1 Top
0.5,
0.5,
0,
// 2 Upper-Right
0.5,
0,
0,
// 3 Right
0.5,
-0.5,
0,
// 4 Lower-Right
0,
-0.5,
0,
// 5 Bottom
-0.5,
-0.5,
0,
// 6 Lower-Left
-0.5,
0,
0,
// 7 Left
-0.5,
0.5,
0
// 8 Upper-Left
];
var indices = [
0,
1,
8,
0,
2,
1,
// Top
0,
2,
1,
0,
3,
2,
// Upper-Right
0,
3,
2,
0,
4,
3,
// Right
0,
4,
3,
0,
5,
4,
// Lower-Right
0,
5,
4,
0,
6,
5,
// Bottom
0,
6,
5,
0,
7,
6,
// Lower-Left
0,
7,
6,
0,
8,
7,
// Left
0,
8,
7,
0,
1,
8
// Upper-Left
];
this.colors = new Array(48).fill(0);
for (var i2 = 0; i2 < 48; i2 += 4) {
this.colors[i2] = 1;
this.colors[i2 + 1] = 0.9;
this.colors[i2 + 2] = 0;
this.colors[i2 + 3] = -0.5;
}
var vertexData = new BABYLON.VertexData();
vertexData.positions = this.positions;
vertexData.indices = indices;
vertexData.colors = this.colors;
vertexData.applyToMesh(this.mesh_, true);
this.mesh_.layerMask = 536870912;
this.mesh_.material = gameScene.getMaterialByName("ui");
this.resize();
}
HitIndicator.prototype.resize = function() {
this.mesh_.scaling.x = G.engine.getRenderWidth();
this.mesh_.scaling.y = G.engine.getRenderHeight();
};
HitIndicator.prototype.update = function(delta) {
for (var i2 = 7; i2 < 48; i2 += 4) {
this.colors[i2] -= (this.colors[i2] + 0.5) / 10 * delta;
}
var mult = Math.pow(0.9, delta);
if (me && me.playing) {
camera.position.x *= mult;
camera.position.z *= mult;
}
this.mesh_.updateVerticesData(
BABYLON.VertexBuffer.ColorKind,
this.colors,
true
);
};
HitIndicator.prototype.hit = function(dx, dz) {
var toAngle = -Math.atan2(dx, -dz);
var a = Math.radRange(toAngle - me.yaw_ + 0.393);
a = Math.floor(a / Math.PI2 * 8);
var vec = new BABYLON.Vector2(
-this.positions[a * 3 + 3],
-this.positions[a * 3 + 4]
).normalize();
camera.position.x = vec.x * 0.03;
camera.position.z = vec.y * 0.03;
this.colors[a * 4 + 7] = 2;
};
function Reticle() {
this.crosshairs = [];
this.shotBrackets = [];
for (var i2 = 0; i2 < 4; i2++) {
this.crosshairs.push(document.getElementById("crosshair" + i2));
this.shotBrackets.push(document.getElementById("shotBracket" + i2));
}
this.crosshairReticle = document.getElementById("crosshairContainer");
this.readyBrackets = document.getElementById("readyBrackets");
this.shotReticle = document.getElementById("shotReticleContainer");
this.redDotReticle = document.getElementById("redDotReticle");
this.reticleDot = document.getElementById("reticleDot");
}
Reticle.prototype.show = function() {
document.getElementById("reticleContainer").className = "";
if (me.weapon.constructor.readySpread) {
this.readyBrackets.className = "notReady";
var size = 0.625 * 100 + "vw";
this.readyBrackets.style.width = size;
this.readyBrackets.style.height = size;
} else {
this.readyBrackets.className = "hideme";
}
this.redDotReticle.className = "hideme";
this.crosshairReticle.className = me.weapon.constructor === DozenGauge ? "hideme" : "";
this.shotReticle.className = me.weapon.constructor === DozenGauge ? "" : "hideme";
};
Reticle.prototype.hide = function() {
document.getElementById("reticleContainer").className = "hideme";
};
Reticle.prototype.hideDot = function() {
this.reticleDot.className = "hideme";
};
Reticle.prototype.showDot = function() {
if (settings.centerDot) {
this.reticleDot.className = "";
}
};
Reticle.prototype.fireDenied = function() {
this.readyBrackets.className = "";
var that = this;
setTimeout(function() {
that.readyBrackets.className = "notReady";
}, 10);
};
Reticle.prototype.setPowerful = function(powerful) {
for (var i2 = 0; i2 < 4; i2++) {
var ch = this.crosshairs[i2];
var sb = this.shotBrackets[i2];
if (powerful) {
ch.classList.remove("normal");
ch.classList.add("powerful");
sb.classList.remove("normal");
sb.classList.add("powerful");
} else {
ch.classList.add("normal");
ch.classList.remove("powerful");
sb.classList.add("normal");
sb.classList.remove("powerful");
}
}
};
Reticle.prototype.update = function(delta) {
camera.forwardRay = camera.getForwardRay();
camera.forwardRay.origin = me.actor.eye.getAbsolutePosition();
if (me.weapon) {
var spread = me.weapon.accuracy;
if (me.weapon.constructor === DozenGauge) {
var size = spread * (200 / camera.fov);
this.shotReticle.style.width = size + "vh";
this.shotReticle.style.height = size + "vh";
} else {
var size = spread * (50 / camera.fov);
for (var i2 = 0; i2 < 4; i2++) {
var ch = this.crosshairs[i2];
ch.style.transform = "rotate(" + i2 * 90 + "deg) translateY(calc(" + size + "vh + 0.12em))";
}
}
camera.forwardRay.direction.scaleInPlace(1e3);
var res = Collider.rayCollidesWithMap(camera.forwardRay.origin, camera.forwardRay.direction, Collider.projectileCollidesWithCell);
if (res) {
var range = BABYLON.Vector3.Distance(camera.forwardRay.origin, res.pick.pickedPoint);
camera.forwardRay.range = range;
if (me.weapon.constructor.minRange) {
if (range - 0.01 >= me.weapon.constructor.minRange) {
this.readyBrackets.className = "ready";
} else {
this.readyBrackets.className = "notReady";
}
}
} else {
if (me.weapon.constructor.minRange)
this.readyBrackets.className = "ready";
camera.forwardRay.range = 1e6;
}
if (me.weapon.constructor.burst) {
if (camera.fov - me.weapon.actor.scopeFov < 6e-3) {
this.redDotReticle.className = "";
} else {
this.redDotReticle.className = "hideme";
}
}
}
};
Reticle.prototype.resize = function() {
};
function gaTrackShareEvents() {
const currentGameType = vueData.gameTypes.find(({ value }) => value === gameType);
const gA = vueData.googleAnalytics;
gaSendEvents([
[gA.cat.play, gA.action.shareGameCopy, `Map - ${minMap.name}`, ""],
[gA.cat.play, gA.action.shareGameCopy, currentGameType.locKey ? `Game type - ${currentGameType.locKey}` : "n/a", ""],
[gA.cat.play, gA.action.shareGameCopy, `Play type - ${joinedAs}`, ""]
]);
}
function createInviteLink() {
var root = dynamicContentPrefix == "" ? parsedUrl.root : dynamicContentPrefix;
var url = root + "#" + gameCode;
const linkToShare = crazysdk.inviteLink({ "crazyShare": gameCode });
const shareURL = !crazyGamesActive ? url : linkToShare;
return shareURL;
}
function inviteFriends() {
vueApp.showShareLinkPopup(createInviteLink());
autoInvite = false;
}
function copyFriendCode(codeEl) {
codeEl.select();
gaTrackShareEvents();
try {
if (!navigator.clipboard) {
document.execCommand("copy");
} else {
navigator.clipboard.writeText(codeEl.value);
}
} catch (err) {
console.log("Unable to copy to clipboard");
}
}
function isMeshVisible(mesh2, offset) {
if (freezeFrame)
return true;
var oy = offset || mesh2.getBoundingInfo().boundingBox.center.z;
var dx = mesh2.position.x - camera.globalPosition.x;
var dy = mesh2.position.y + oy - camera.globalPosition.y;
var dz = mesh2.position.z - camera.globalPosition.z;
var distance = Math.length3(dx, dy, dz);
var dv = Math.normalize3({ x: dx, y: dy, z: dz }, 0.9);
var x = camera.globalPosition.x;
var y = camera.globalPosition.y;
var z = camera.globalPosition.z;
var collisions = 0;
for (var i2 = 0; i2 < distance - 0.9; i2 += 0.9) {
x += dv.x;
y += dv.y;
z += dv.z;
if (x < 0 || x >= map.width || z < 0 || z >= map.depth || y < 0 || y >= map.height) {
break;
}
var cell = map.data[Math.floor(x)][Math.floor(y)][Math.floor(z)];
if (cell.idx) {
var m = mapMeshes[cell.idx];
if (m.colliderType == "full" && !m.softness && m.shortName !== "barrier") {
collisions++;
if (collisions == 2) {
return false;
}
}
}
}
return true;
}
function openEquipInGame() {
G.engine.stopRenderLoop();
paperDoll.startRendering();
}
function closeEquipInGame(ignoreResize) {
G.engine.stopRenderLoop();
startRendering(ignoreResize);
equipmentWasChanged = true;
if (chatting) {
chatInEl.focus();
}
}
function resetGameUI() {
chatInEl = document.getElementById("chatIn");
chatOutEl = document.getElementById("chatOut");
killEl = document.getElementById("killTicker");
var clearChildren = function(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
};
var playerList = document.getElementById("playerList");
clearChildren(playerList);
var slotTemplate = document.getElementById("playerSlot");
for (var i2 = 0; i2 < 20; i2++) {
var slot = slotTemplate.cloneNode(true);
playerList.appendChild(slot);
}
chatOutEl.innerHTML = "";
if (settings.enableChat == true) {
initChatIn();
chatOutEl.style.display = "block";
chatInEl.style.display = "block";
}
killEl.innerHTML = "";
chatOutEl.value = "";
document.getElementById("killBox").style.display = "none";
document.getElementById("deathBox").style.display = "none";
document.getElementById("scopeBorder").style.display = "none";
document.getElementById("spatulaPlayer").className = "drop";
document.getElementById("spectate").style.display = "none";
document.getElementById("teamScores").style.display = gameType == GameType.ctf ? "block" : "none";
document.getElementById("captureContainer").style.display = gameType == GameType.king ? "block" : "none";
document.getElementById("captureIconContainer").style.display = "none";
document.getElementById("shellStreakMessage").classList.remove("appear");
document.getElementById("shellStreakMessage").classList.add("disappear");
document.getElementById("shellStreakCaption").style.visibility = "hidden";
document.getElementById("eggBreakerContainer").className = "off";
document.getElementById("playerList").style.pointerEvents = "auto";
if (reticle)
reticle.setPowerful(false);
console.log("resetGameUI");
}
function updateTeamUI() {
for (var i2 = 1; i2 <= 2; i2++) {
var numEl = document.getElementById("teamScoreNum" + i2);
numEl.innerText = metaGame.teamScore[i2];
var teamEl = document.getElementById("teamScore" + i2);
if (spatula) {
if (spatula.controlledByTeam == i2) {
teamEl.classList.replace("inactive", "active");
} else if (spatula.lastControlTeam != i2) {
teamEl.classList.replace("active", "inactive");
}
}
}
}
function addCanvasListeners() {
console.log("Event listeners added");
canvas.focus();
canvas.style.pointerEvents = "all";
canvas.addEventListener("mousedown", onCanvasMouseDown, false);
canvas.addEventListener("mouseup", onCanvasMouseUp, false);
canvas.addEventListener("pointermove", onCanvasMouseMove);
canvas.addEventListener("wheel", onCanvasMouseWheel);
addEventListener("gamepadbuttondown", onGamepadButtonDown);
}
function removeCanvasListeners() {
console.log("Event listeners removed");
canvas.style.pointerEvents = "none";
canvas.removeEventListener("mousedown", onCanvasMouseDown);
canvas.removeEventListener("mouseup", onCanvasMouseUp);
canvas.removeEventListener("pointermove", onCanvasMouseMove);
canvas.removeEventListener("wheel", onCanvasMouseWheel);
removeEventListener("gamepadbuttondown", onGamepadButtonDown);
}
function onGamepadButtonDown(e2) {
if (e2.detail == 8) {
document.exitPointerLock();
}
}
var MetaGame = class {
constructor() {
this.teamScore = [0, 0, 0];
this.suppressSound = true;
this.lastLeadingTeam = 1;
}
update() {
}
scoreKill(killer, victim) {
}
_unPackState(commIn) {
this.unPackState(commIn);
this.suppressSound = false;
}
playSound(name) {
if (!this.suppressSound)
BAWK.play(name);
}
reset() {
if (me)
me.canTakeTeamBonus = true;
metaGame.teamScore = [0, 0, 0];
for (var i2 = 0; i2 < playerLimit; i2++) {
var player = players[i2];
if (player) {
player.score = 0;
player.stats.streak = 0;
}
}
rebuildPlayerList();
}
getTeamWithMostKills() {
let leadingTeam = this.lastLeadingTeam;
let teamKills = [0, 0, 0];
for (let i2 = 0; i2 < playerLimit; i2++) {
let player = players[i2];
if (player) {
teamKills[player.team] += player.score;
}
}
if (teamKills[1] > teamKills[2]) {
leadingTeam = 1;
} else if (teamKills[2] > teamKills[1]) {
leadingTeam = 2;
}
this.lastLeadingTeam = leadingTeam;
return leadingTeam;
}
getTeamWithHighestScore() {
let leadingTeam = this.lastLeadingTeam;
if (this.teamScore[1] > this.teamScore[2]) {
leadingTeam = 1;
} else if (this.teamScore[2] > this.teamScore[1]) {
leadingTeam = 2;
}
this.lastLeadingTeam = leadingTeam;
return leadingTeam;
}
static otherTeam(victim) {
return victim.team == 1 ? 2 : 1;
}
};
var MetaGameUI = class {
constructor() {
}
update() {
}
render() {
}
sortPlayerList() {
}
sortPlayerListByKills(playerIdxs) {
playerIdxs.sort((a, b2) => {
return players[b2].score - players[a].score;
});
}
sortPlayerListByTeamKills(playerIdxs) {
this.sortPlayerListByKills(playerIdxs);
let leader = metaGame.getTeamWithMostKills();
this.sortPlayerListByLeadingTeam(playerIdxs, leader);
}
sortPlayerListByTeamScore(playerIdxs) {
this.sortPlayerListByKills(playerIdxs);
let leader = metaGame.getTeamWithHighestScore();
this.sortPlayerListByLeadingTeam(playerIdxs, leader);
}
// Helper function - do not call directly
sortPlayerListByLeadingTeam(playerIdxs, leadingTeam) {
playerIdxs.sort((a, b2) => {
if (players[b2].team == leadingTeam)
return 1;
if (players[a].team == leadingTeam)
return -1;
return 0;
});
}
timeToPlayVideoAd() {
return null;
}
playSound(name) {
if (!metaGame.suppressSound)
BAWK.play(name);
}
};
var MetaGameFFA = class extends MetaGame {
constructor() {
super();
}
};
var MetaGameUIFFA = class extends MetaGameUI {
constructor() {
super();
}
sortPlayerList(playerIdxs) {
this.sortPlayerListByKills(playerIdxs);
}
};
var MetaGameTeams = class extends MetaGame {
constructor() {
super();
}
scoreKill(forTeam) {
this.teamScore[forTeam]++;
}
unPackState(commIn) {
this.teamScore[1] = commIn.unPackInt16U();
this.teamScore[2] = commIn.unPackInt16U();
}
};
var MetaGameUITeams = class extends MetaGameUI {
constructor() {
super();
}
sortPlayerList(playerIdxs) {
this.sortPlayerListByTeamKills(playerIdxs);
}
};
var MetaGameSpatula = class extends MetaGame {
constructor() {
super();
}
reset() {
super.reset();
this.resetSpatula();
}
resetSpatula() {
spatula.actor.dispose();
spatula = null;
var el = document.getElementById("spatulaPlayer");
el.className = "drop";
}
scoreKill(killer, victim) {
if (!spatula.actor && spatula.controlledBy == victim.id) {
spatula.drop();
}
var otherTeam = MetaGame.otherTeam(victim);
if (spatula.controlledByTeam == otherTeam) {
this.teamScore[otherTeam]++;
updateTeamUI();
}
}
unPackState(commIn) {
this.teamScore[1] = commIn.unPackInt16U();
this.teamScore[2] = commIn.unPackInt16U();
let p = {
x: commIn.unPackFloat(),
y: commIn.unPackFloat(),
z: commIn.unPackFloat()
};
let controlledBy = commIn.unPackInt8U();
let controlledByTeam = commIn.unPackInt8U();
if (!spatula) {
spatula = new Spatula(gameScene, p);
spatula.controlledBy = controlledBy;
spatula.controlledByTeam = controlledByTeam;
} else {
spatula.x = p.x;
spatula.y = p.y;
spatula.z = p.z;
if (spatula.controlledBy != controlledBy) {
var teamLabels = [
"",
'' + vueApp.loc["team_blue"] + "
",
'' + vueApp.loc["team_red"] + "
"
];
if (controlledBy == 255) {
if (me.playing) {
var el = document.getElementById("gameMessage");
el.innerHTML = teamLabels[spatula.controlledByTeam];
el.innerHTML += getLocText("ingame_dropped_the_spatula");
el.className = "show";
setTimeout(() => {
el.className = "hide";
}, 3e3);
}
spatula.drop(p);
} else {
if (me.playing) {
var el = document.getElementById("gameMessage");
el.innerHTML = teamLabels[controlledByTeam];
el.innerHTML += getLocText("ingame_captured_the_spatula");
el.className = "show";
setTimeout(() => {
el.className = "hide";
}, 3e3);
}
let player = players[controlledBy];
if (player && player.playing) {
spatula.capture(players[controlledBy]);
}
}
}
}
updateTeamUI();
}
};
var MetaGameUISpatula = class extends MetaGameUI {
constructor() {
super();
}
sortPlayerList(playerIdxs) {
this.sortPlayerListByTeamScore(playerIdxs);
}
};
var MetaGameKing = class _MetaGameKing extends MetaGame {
constructor() {
super();
this.init();
}
init() {
this.activeZone = null;
this.teams = null;
this.progress = null;
this.numCapturing = null;
this.teamsBalanced = false;
this.state = _MetaGameKing.state.capturing;
}
reset() {
super.reset();
this.init();
}
update() {
if (!this.activeZone)
return;
if (this.state == _MetaGameKing.state.takeover) {
if (this.progress > 0) {
this.progress -= _MetaGameKing.takeOverSpeed;
}
} else if (this.state == _MetaGameKing.state.capturing) {
if (this.teams == 1 || this.teams == 2) {
let captureSpeed = _MetaGameKing.captureSpeeds[this.numCapturing - 1];
this.progress += captureSpeed;
}
}
}
unPackState(commIn) {
let oldActiveZone = this.activeZone;
this.state = commIn.unPackInt8U();
this.activeZone = commIn.unPackInt8U();
this.teams = commIn.unPackInt8U();
this.progress = commIn.unPackInt16U();
this.numCapturing = commIn.unPackInt8U();
this.teamScore[1] = commIn.unPackInt8U();
this.teamScore[2] = commIn.unPackInt8U();
console.log("ACTIVE ZONE IS NOW", this.activeZone);
switch (this.state) {
case _MetaGameKing.state.win:
munitionsManager.removeAll();
roundEnded = true;
metaGameUI.win();
this.playSound("kotc_roundend");
break;
case _MetaGameKing.state.start:
if (roundEnded) {
roundEnded = false;
this.reset();
if (playerCount[1] + playerCount[2] > 2) {
var el = document.getElementById("gameMessage");
el.innerHTML = getLocText("ingame_coop_shuffle");
el.className = "show";
setTimeout(() => {
el.className = "hide";
}, 3e3);
}
}
break;
case _MetaGameKing.state.score:
this.playSound("kotc_pointscore");
break;
case _MetaGameKing.state.contested:
this.playSound("kotc_contested");
break;
}
if (this.activeZone && this.activeZone != oldActiveZone) {
this.playSound("kotc_zonespawn");
}
metaGameUI.setCaptureState(this.teams);
}
};
var MetaGameUIKing = class _MetaGameUIKing extends MetaGameUI {
constructor() {
super();
this.captureBarEl = document.getElementById("captureBar");
this.captureBarTextEl = document.getElementById("captureBarText");
this.captureIconContainer = document.getElementById("captureIconContainer");
this.captureIcon = document.getElementById("captureIcon");
this.captureRingContainer = document.getElementById("captureRingContainer");
this.captureRing = document.getElementById("captureRing");
this.captureIconCaption = document.getElementById("captureIconCaption");
this.previousCapturingTeam = 0;
this.teamScoreEl = [
null,
document.getElementById("captureScoreBlue"),
document.getElementById("captureScoreRed")
];
}
update() {
if (metaGame.activeZone == 0) {
if (this.captureBarTextEl.innerHTML == " " && (playerCount[1] == 0 || playerCount[2] == 0)) {
this.captureBarTextEl.innerText = getLocText("ingame_coop_waiting");
}
return;
}
if (metaGame.state == MetaGameKing.state.takeover) {
let pct = Math.max(metaGame.progress, 0);
this.setBarProgress(1 - pct / MetaGameKing.takeOverTime);
let lerp2 = Math.cos(now / 100 % (Math.PI * 2)) * 0.5 + 0.5;
BABYLON.Color3.LerpToRef(teamUI[metaGame.teams == 1 ? 2 : 1].lightZone, _MetaGameUIKing.zoneColor.takeover, lerp2, _MetaGameUIKing.color);
capZoneMeshes[metaGame.activeZone - 1].colorMult = _MetaGameUIKing.color;
} else if (metaGame.teams == 1 || metaGame.teams == 2) {
let pct = Math.min(metaGame.progress, 1200);
this.setBarProgress(pct / 1200);
}
if (metaGame.state == MetaGameKing.state.contested) {
let lerp2 = Math.cos(now / 100 % (Math.PI * 2)) * 0.5 + 0.5;
BABYLON.Color3.LerpToRef(teamUI[1].lightZone, teamUI[2].lightZone, lerp2, _MetaGameUIKing.color);
capZoneMeshes[metaGame.activeZone - 1].colorMult = _MetaGameUIKing.color;
}
if (me && metaGame.activeZone) {
let pos = capZoneMeshes[metaGame.activeZone - 1].capIconPosition;
let range = Math.length3(me.x_ - pos.x, me.y_ - pos.y, me.z_ - pos.z);
let opacity = Math.max(0, Math.min(range * 0.5 - 1 + Math.abs(me.y_ - pos.y + 0.4) * 0.5, 0.6));
this.captureIconContainer.style.opacity = opacity;
this.captureIconCaption.innerText = Math.floor(range * 2) + "M";
}
}
render() {
let el = this.captureIconContainer;
if (!metaGame.activeZone) {
el.classList.remove("on");
return;
}
el.classList.add("on");
let mat = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
let pos = capZoneMeshes[metaGame.activeZone - 1].capIconPosition;
let scale = G.engine.getHardwareScalingLevel();
let width = G.engine.getRenderWidth() * scale;
let height = G.engine.getRenderHeight() * scale;
let screenPos = BABYLON.Vector3.TransformCoordinates(pos, mat);
screenPos.y *= -1;
let dir = camera.getDirection(BABYLON.Vector3.Forward());
let myPos = camera.globalPosition;
let dx = pos.x - myPos.x;
let dy = pos.y - myPos.y;
let dz = pos.z - myPos.z;
let len = Math.length3(dx, dy, dz);
let dot = (dir.x * dx + dir.y * dy + dir.z * dz) / len;
let x = screenPos.x;
let y = screenPos.y;
let osx, osy;
if (dot < 0) {
x *= -1;
y *= -1;
osx = Math.min(1, 1 / Math.abs(x));
osy = Math.min(1, 1 / Math.abs(y));
x *= osy;
y *= osx;
let d;
if (Math.abs(x) > Math.abs(y)) {
x = Math.sign(x);
} else {
y = Math.sign(y);
}
} else {
osx = Math.min(1, 1 / Math.abs(x));
osy = Math.min(1, 1 / Math.abs(y));
x *= osy;
y *= osx;
}
x = x * (width / 2) + width / 2;
y = y * (height / 2) + height / 2;
x = Math.max(Math.min(x, width * 0.9), width * 0.1);
y = Math.max(Math.min(y, height * 0.9), height * 0.1);
el.style.transform = "translate(" + x + "px," + y + "px)";
}
setCaptureState(teams) {
this.teamScoreEl[1].innerText = metaGame.teamScore[1] + " / " + MetaGameKing.goalScore;
this.teamScoreEl[2].innerText = metaGame.teamScore[2] + " / " + MetaGameKing.goalScore;
let zoneMesh = null;
if (metaGame.activeZone) {
zoneMesh = capZoneMeshes[metaGame.activeZone - 1];
}
switch (metaGame.state) {
case MetaGameKing.state.win:
this.captureBarTextEl.innerText = getLocText("ingame_coop_nextround");
this.captureBarEl.className = "empty";
this.captureRing.className = "empty";
this.captureIcon.setAttribute("class", "empty");
this.previousCapturingTeam = 0;
break;
case MetaGameKing.state.score:
case MetaGameKing.state.start:
this.captureBarTextEl.innerHTML = " ";
this.captureBarEl.className = "empty";
this.captureRing.className = "empty";
this.captureIcon.setAttribute("class", "empty");
this.previousCapturingTeam = 0;
break;
case MetaGameKing.state.unclaimed:
this.captureBarTextEl.innerText = getLocText("ingame_coop_find");
this.captureBarEl.className = "empty";
this.captureRing.className = "empty";
this.captureIcon.setAttribute("class", "empty");
zoneMesh.colorMult = _MetaGameUIKing.zoneColor.unclaimed;
break;
case MetaGameKing.state.capturing:
var classes = ["", "blue", "red"];
this.captureBarTextEl.innerText = getLocText(teamUI[teams].name).toUpperCase() + " " + getLocText("ingame_coop_capturing") + " (" + metaGame.numCapturing + "X)";
this.captureBarEl.className = classes[teams];
this.captureRing.className = classes[teams];
this.captureIcon.setAttribute("class", classes[teams]);
if (teams > 0 && teams != this.previousCapturingTeam) {
this.previousCapturingTeam = teams;
if (me.team == teams) {
this.playSound("kotc_capturing_player");
} else {
this.playSound("kotc_capturing_opponents");
}
}
zoneMesh.colorMult = teamUI[teams].lightZone;
break;
case MetaGameKing.state.abandoned:
var classes = ["", "blueAbandoned", "redAbandoned"];
this.captureBarTextEl.innerText = getLocText(teamUI[teams].name).toUpperCase() + " " + getLocText("ingame_coop_capturing");
this.captureBarEl.className = classes[teams];
this.captureRing.className = classes[teams];
this.captureIcon.setAttribute("class", classes[teams]);
zoneMesh.colorMult = teamUI[teams].darkZone;
break;
case MetaGameKing.state.contested:
this.captureBarTextEl.innerText = getLocText("ingame_coop_contested");
this.captureBarEl.className = "contested";
this.captureRing.className = "contested";
this.captureIcon.setAttribute("class", "contested");
break;
case MetaGameKing.state.takeover:
this.captureBarTextEl.innerText = getLocText("ingame_coop_takeover");
this.captureBarEl.className = "takeover";
this.captureRing.className = "takeover";
this.captureIcon.setAttribute("class", "takeover");
break;
}
for (let i2 = 0; i2 < capZoneMeshes.length; i2++) {
let mesh2 = capZoneMeshes[i2];
mesh2.visibility = metaGame.activeZone == i2 + 1;
}
}
setBarProgress(pct) {
let style = this.captureBarEl.style;
style.transform = "scaleX(" + pct + ")";
let fpct = (1 - pct) * 100;
this.captureRingContainer.style.transform = "translateY(" + fpct + "%)";
this.captureRing.style.transform = "translateY(" + -fpct + "%)";
}
win() {
this.setCaptureState(0);
let el = document.getElementById("bigMessageContainer");
el.style.display = "block";
let teamWon = metaGame.teamScore[1] > metaGame.teamScore[2] ? 1 : 2;
document.documentElement.style.setProperty("--ss-big-message-border-color", teamUI[teamWon].lightColor);
document.getElementById("bigMessage").innerHTML = '' + getLocText(teamUI[teamWon].name).toUpperCase() + ' ' + getLocText("ingame_coop_win") + "";
if (teamWon == me.team && me.canTakeTeamBonus) {
document.getElementById("bigMessageCaption").innerHTML = getLocText("ingame_coop_bonus") + ' +250
';
} else {
document.getElementById("bigMessageCaption").innerHTML = getLocText("ingame_coop_nextroundbig");
}
setTimeout(() => {
el.style.display = "none";
}, 5e3);
}
timeToPlayVideoAd() {
if (metaGame.teamScore[1] === 4 || metaGame.teamScore[2] === 4) {
return false;
}
return null;
}
sortPlayerList(playerIdxs) {
this.sortPlayerListByTeamScore(playerIdxs);
}
};
MetaGameUIKing.zoneColor = {
unclaimed: new BABYLON.Color3(0.3, 0.3, 0.3),
takeover: new BABYLON.Color3(0.8, 0.8, 0.8)
};
MetaGameUIKing.color = new BABYLON.Color3();
function getCssProp(prop) {
return getComputedStyle(document.documentElement).getPropertyValue(prop);
}
function getColor3FromCssProp(prop) {
let rgb = getCssProp(prop);
rgb = rgb.match(/^\s*rgba?\((\d+),\s*(\d+),\s*(\d+)(,\s*\d+\.*\d+)?\)\s*$/);
return BABYLON.Color3.FromInts(rgb[1], rgb[2], rgb[3]);
}
var teamUI = [
null,
{
name: "team_blue",
lightColor: getCssProp("--ss-team-blue-light"),
darkColor: getCssProp("--ss-team-blue-dark"),
lightZone: getColor3FromCssProp("--ss-team-blue-light"),
darkZone: getColor3FromCssProp("--ss-team-blue-dark")
},
{
name: "team_red",
lightColor: getCssProp("--ss-team-red-light"),
darkColor: getCssProp("--ss-team-red-dark"),
lightZone: getColor3FromCssProp("--ss-team-red-light"),
darkZone: getColor3FromCssProp("--ss-team-red-dark")
}
];
var MetaGames = [
{ logic: MetaGameFFA, ui: MetaGameUIFFA },
{ logic: MetaGameTeams, ui: MetaGameUITeams },
{ logic: MetaGameSpatula, ui: MetaGameUISpatula },
{ logic: MetaGameKing, ui: MetaGameUIKing }
];
window.console = function(origConsole) {
if (!window.console || !origConsole) {
origConsole = {};
}
var logArray = [];
return {
dir: function() {
origConsole.dir && origConsole.dir.apply(origConsole, arguments);
},
log: function() {
this.addLog(arguments);
origConsole.log && origConsole.log.apply(origConsole, arguments);
},
warn: function() {
this.addLog(arguments);
origConsole.warn && origConsole.warn.apply(origConsole, arguments);
},
error: function() {
this.addLog(arguments);
origConsole.error && origConsole.error.apply(origConsole, arguments);
},
info: function() {
this.addLog(arguments);
origConsole.info && origConsole.info.apply(origConsole, arguments);
},
addLog: function(args) {
var msg = args[0];
if (typeof msg == "object")
msg = JSON.stringify(msg);
logArray.push(msg);
if (logArray.length > 100)
logArray.shift();
},
logArray: function() {
return logArray;
},
clearLog: function() {
logArray = [];
},
debug: function(args) {
origConsole.log(args);
}
};
}(window.console);
function getEquippedItems() {
return G.playerAccount.getEquippedItems();
}
function getItemsOfType(itemType) {
switch (itemType) {
case ItemType2.Hat:
return G.catalog.hats;
case ItemType2.Stamp:
return G.catalog.stamps;
case ItemType2.Primary:
return G.catalog.forClass[G.playerAccount.classIdx].forWeaponSlot[Slot.Primary];
case ItemType2.Secondary:
return G.catalog.forClass[G.playerAccount.classIdx].forWeaponSlot[Slot.Secondary];
case ItemType2.Grenade:
return G.catalog.grenades;
case ItemType2.Melee:
return G.catalog.melee;
default:
return [];
}
}
function getTaggedItems(tag, itemType) {
return G.catalog.getTaggedItems(tag, itemType);
}
function getPremiumItems() {
return G.catalog.getPremiumItems();
}
function isItemOwned(item) {
return G.playerAccount.isItemOwned(item);
}
function renderItemToCanvas(item, canvas2, callback) {
if (item.item_type_id === ItemType2.Stamp) {
itemRenderer.renderStampToCanvas(item, canvas2, callback);
} else {
itemRenderer.renderToCanvas(item, canvas2, callback);
}
}
function tryEquipItem(item, itemTypeId) {
itemTypeId = itemTypeId || item.item_type_id;
if (item === null || isItemOwned(item) || item.unlock === "default") {
switch (itemTypeId) {
case ItemType2.Hat:
G.playerAccount.hatItem = item;
break;
case ItemType2.Stamp:
G.playerAccount.stampItem = item;
break;
case ItemType2.Primary:
G.playerAccount.pickWeapon(Slot.Primary, item);
break;
case ItemType2.Secondary:
G.playerAccount.pickWeapon(Slot.Secondary, item);
break;
case ItemType2.Grenade:
G.playerAccount.grenadeItem = item;
break;
case ItemType2.Melee:
G.playerAccount.meleeItem = item;
break;
}
}
}
function setShellColor(colorIdx) {
G.playerAccount.colorIdx = colorIdx;
paperDoll.poseWithColor(colorIdx);
}
function resetPaperDoll() {
let items = G.playerAccount.getEquippedItems();
items[ItemType2.Grenade] = null;
items[ItemType2.Melee] = null;
paperDoll.posingItems = {
[ItemType2.Primary]: null,
[ItemType2.Secondary]: null,
[ItemType2.Grenade]: null,
[ItemType2.Melee]: null,
[ItemType2.Hat]: null,
[ItemType2.Stamp]: null
};
paperDoll.poseWithItems(items);
paperDoll.poseWithColor(G.playerAccount.colorIdx);
}
G.resetPaperDoll = resetPaperDoll;
function signIn() {
firebaseSignInTimerStart = /* @__PURE__ */ new Date();
G.playerAccount = new PlayerAccount();
const rawLocalLoadOut = localStore.getItem("localLoadOut");
if (rawLocalLoadOut) {
const localLoadOut = JSON.parse(rawLocalLoadOut);
G.playerAccount.applyLocalLoadout(localLoadOut.items);
} else {
G.playerAccount.applyRandomLoadout();
}
console.log("Start account search with Firebase...");
if (parsedUrl.query.sandbox) {
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
}
firebase.auth().onAuthStateChanged(function(signedInUser) {
if (upgradingAnon && !hasValue(signedInUser)) {
return;
}
if (signedInUser) {
firebaseUser = signedInUser;
if (firebaseUser.isAnonymous) {
console.log("Firebase: anonymous user");
anonymousUser = firebaseUser;
if (!hasAccount) {
creatingAccount = true;
}
} else {
console.log("Firebase: auth provider: " + firebaseUser.providerData[0].providerId);
if (!firebaseUser.emailVerified && firebaseUser.providerData[0].providerId == "password") {
console.log("Firebase: email not yet verified");
showResendEmailPopup = true;
}
}
firebaseAccountFound();
} else {
console.log("Firebase: no account found");
noFirebaseAccount();
}
});
}
function firebaseAccountFound() {
if (signingIn) {
return;
}
signingIn = true;
upgradingAnon = false;
hasAccount = true;
firebaseUser.getIdToken(true).then((firebaseToken) => {
api_auth(firebaseToken, authSuccess, authFailure, authClosed);
}).catch(function(error) {
console.log(error);
signingIn = false;
});
if (firebaseUser.providerData.length > 0) {
loginProviderId = firebaseUser.providerData[0].providerId;
}
if (firebaseUser.photoURL && firebaseUser.providerData && firebaseUser.providerData.length > 0) {
var url = firebaseUser.photoURL;
vueApp.photoUrl = url;
}
}
function noFirebaseAccount() {
console.log("No account created yet :(");
signingIn = false;
ready_auth = true;
hasAccount = false;
rmItemsLocalStore();
vueApp.authCompleted();
return;
}
var getGameParams = null;
function createAnonAccountTrigger(params) {
vueApp.showSpinner("connecting", "please_wait");
return firebase.auth().signInAnonymously().then(() => {
firebase.auth().onAuthStateChanged((signedInUser) => {
hasAccount = true;
firstGamePlayed = true;
if (signedInUser !== null) {
if (params && signedInUser.isAnonymous) {
hasAccount = false;
getGameParams = params;
}
}
});
}).catch(function(error) {
console.debug("Failed Firebase anonymous signin, code: {0}, msg: {1}".format(error.code, error.message));
});
}
function sendFirebaseVerificationEmail() {
console.log("sending Firebase email verification");
firebaseUser.sendEmailVerification();
}
function authSuccess(authResponse) {
if (authResponse.hasOwnProperty("dateModified") && authResponse.hasOwnProperty("dateCreated")) {
const diff = Math.floor(Math.abs(new Date(authResponse.dateModified) - new Date(authResponse.dateCreated)) / 36e5);
hasTimesPlayed = diff > 1;
}
if (authResponse.hasOwnProperty("banRemaining")) {
var remaining = authResponse.banRemaining;
let banExpireString;
let fields = remaining.split(":");
let hours = parseInt(fields[0]);
let minutes = parseInt(fields[1]);
if (hours > 24) {
banExpireString = `${Math.floor(hours / 24)} ${getLocText("time_days")}`;
} else if (hours > 0) {
banExpireString = `${hours} ${getLocText("time_hours")}`;
} else {
banExpireString = `${minutes} ${getLocText("time_minutes")}`;
}
vueApp.showBannedPopup(banExpireString);
} else if (authResponse.error) {
console.log("accountDataResponse Error: " + JSON.stringify(accountDataResponse.error));
} else {
G.playerAccount.signedIn(firebaseUser, authResponse);
vueApp.authCompleted();
ready_auth = true;
setTimeout(() => G.playerAccount.syncToServer(), 1e3);
checkStartChicknWinner(true);
if (signinClicked) {
if (tryMidMonthRewardAgain) {
tryMidMonthNewYolkerReward();
}
if (G.showSigninBonus) {
tryShowSigninBonus();
G.showSigninBonus = false;
}
rmItemsLocalStore();
}
if (anonymousUser !== null) {
ga("set", "vip_status", "NoVIP");
} else {
if (parsedUrl.query.signInPrompt && parsedUrl.query.closeAfterSign) {
window.close();
}
api_getPlayerSubStatus((getData) => {
if (getData.outData === null) {
ga("set", "vip_status", "NoVIP");
} else if (getData.outData[0].hasOwnProperty("active") && getData.outData[0].active) {
ga("set", "vip_status", "IsVIP");
} else {
ga("set", "vip_status", "WasVIP");
}
}, (data2) => console.log("api_getPlayerSubStatus error", data2));
doTwitchEntitlementsCheck();
}
console.log("Signed in");
if (!hasAccount && getGameParams !== null) {
console.log("Nonaccount is now anon. Time for play");
hasAccount = true;
disablePlay(false);
play(getGameParams);
}
}
creatingAccount = false;
}
function doTwitchEntitlementsCheck() {
api_twitchPlayerEntitlements((data2) => {
console.log("Twitch Entitlements status", data2);
switch (data2.status) {
case "SUCCESS":
if (data2.eggsGiven > 0) {
api_checkBalance();
}
let giveItems = [];
if (hasValue(data2.itemIds) && data2.itemIds.length > 0) {
giveItems = G.catalog.findItemsByIds(data2.itemIds);
giveItems.forEach((i2) => {
if (!G.playerAccount.isItemOwned(i2)) {
G.playerAccount.inventory.push(i2);
console.log("Reward item given, id: " + i2.id);
}
});
}
vueApp.showGiveStuffPopup("give_stuff_twitch_title", data2.eggsGiven, giveItems, data2.type);
break;
case "ACCOUNT_DEACTIVATED":
console.log("Twitch ACCOUNT_DEACTIVATED");
break;
default:
break;
}
}, (err) => console.log("api_twitchPlayerEntitlements error", err));
}
function authFailure() {
console.log("authorization failed");
ga("send", "event", vueData.googleAnalytics.cat.playerStats, vueData.googleAnalytics.action.signIn, vueData.googleAnalytics.label.signInAuthFailed);
Loader2.hide();
vueApp.authCompleted();
}
function authClosed(code) {
console.log("auth ws closed, code: " + code);
if (code === 1006) {
vueApp.showGenericPopup("signin_failed_title", "signin_failed", "ok");
return;
}
signingIn = false;
}
function showSignInDialog() {
if (!firebaseUi) {
firebaseUi = new firebaseui.auth.AuthUI(firebase.auth());
}
var firebaseUiConfig = firebaseUiCreateConfig();
firebaseUi.start("#firebaseui-auth-container", firebaseUiConfig);
signinClicked = true;
}
function firebaseUiCreateConfig() {
return {
autoUpgradeAnonymousUsers: true,
callbacks: {
signInSuccessWithAuthResult: firebaseUiSignInSuccess,
signInFailure: firebaseUiSignInFailure,
uiShown: function(e2) {
console.log("UI: showed firebase UI");
const uiContainer = document.querySelector(".firebaseui-idp-list");
if (uiContainer) {
const fbBtnLi = document.createElement("li");
const fbBtn = document.createElement("button");
const fbIcon = document.createElement("span");
const fbIconImg = document.createElement("img");
const fbBtnText = document.createElement("span");
fbBtn.onclick = () => {
vueApp.fbTransferAccountSignin();
};
fbBtn.className = "firebaseui-idp-button mdl-button mdl-js-button mdl-button--raised firebaseui-idp-facebook firebaseui-id-idp-button";
fbBtn.style.backgroundColor = "#3b5998";
fbBtnText.className = "firebaseui-idp-text firebaseui-idp-text-long";
fbBtnText.textContent = "Sign in with Facebook";
fbIcon.className = "firebaseui-idp-icon-wrapper";
fbIconImg.className = "firebaseui-idp-icon";
fbIconImg.src = "https://www.gstatic.com/firebasejs/ui/2.0.0/images/auth/facebook.svg";
fbBtnLi.className = "firebaseui-list-item";
fbIcon.appendChild(fbIconImg);
fbBtn.appendChild(fbIcon);
fbBtn.appendChild(fbBtnText);
fbBtnLi.appendChild(fbBtn);
uiContainer.appendChild(fbBtnLi);
}
}
// TODO: Remove Cancel button?
},
credentialHelper: firebaseui.auth.CredentialHelper.NONE,
signInFlow: "popup",
//signInSuccessUrl: 'https://shellshock.io',
signInOptions: [
// Leave the lines as is for the providers you want to offer your users.
{
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
requireDisplayName: false
},
// firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.GoogleAuthProvider.PROVIDER_ID
],
// Terms of service url.
tosUrl: "http://www.bluewizard.com/terms"
};
}
function firebaseUiSignInSuccess(firebaseResult, redirectUrl) {
firebaseUser = firebaseResult.user;
var emailVerified = firebaseUser.emailVerified;
var credential = firebaseResult.credential;
var isNewUser = firebaseResult.additionalUserInfo.isNewUser;
var providerId = firebaseResult.additionalUserInfo.providerId;
var operationType = firebaseResult.operationType;
vueApp.hideFirebaseSignIn();
if (providerId == "password" && !emailVerified) {
sendFirebaseVerificationEmail();
}
console.log("Authing Firebase ID");
firebaseAccountFound();
return false;
}
function firebaseUiSignInFailure(error) {
vueApp.hideFirebaseSignIn();
console.log("Firebase: sign in failure, error code: " + error.code);
if (error.code === "firebaseui/anonymous-upgrade-merge-conflict") {
upgradingAnon = true;
firebase.auth().signInWithCredential(error.credential);
anonymousUser.delete();
setTimeout(() => {
vueApp.$nextTick(() => {
vueApp.urlParamSet = vueApp.urlParams ? true : null;
vueApp.shellShockUrlParamaterEvents();
});
}, 2e3);
} else {
return Promise.resolve();
}
}
function signOut() {
firebase.auth().signOut().then(function() {
G.playerAccount = new PlayerAccount();
G.playerAccount.loggingOut();
G.playerAccount.applyRandomLoadout();
productBlockAds = false;
if (!pokiActive && !crazyGamesActive) {
initVideoAds();
vueApp.showTitleScreenAd();
}
setTimeout(() => vueApp.setDarkOverlay(false), 1500);
}, function(err) {
console.log(err);
});
ga("set", "dimension4", "noVip");
ga("send", "event", vueData.googleAnalytics.cat.playerStats, vueData.googleAnalytics.action.signIn, vueData.googleAnalytics.label.signInOut);
vueApp.photoUrl = null;
rmItemsLocalStore();
checkStartChicknWinner(true);
signinClicked = false;
}
var ws;
var metaGame;
var metaGameUI;
var isTeamGame = false;
var me;
var meId;
G.BABYLON = BABYLON;
function startShellShockers(languageCode) {
let idStr = "";
let testGl = document.createElement("canvas").getContext("webgl");
idStr += testGl.getParameter(testGl.VERSION);
let rendererInfo = testGl.getExtension("WEBGL_debug_renderer_info");
if (rendererInfo != null) {
idStr += testGl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
idStr += testGl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
}
idStr += navigator.userAgent + navigator.language;
clientId = 1;
for (let c in idStr) {
clientId = clientId * idStr.charCodeAt(c) % Number.MAX_SAFE_INTEGER;
}
clientId += (navigator.hardwareConcurrency + navigator.maxTouchPoints) % Number.MAX_SAFE_INTEGER;
var config = {
apiKey: "AIzaSyDP4SIjKaw6A4c-zvfYxICpbEjn1rRnN50",
authDomain: "shellshockio-181719.firebaseapp.com",
databaseURL: "https://shellshockio-181719.firebaseio.com",
projectId: "shellshockio-181719",
storageBucket: "shellshockio-181719.appspot.com",
messagingSenderId: "68327206324"
};
firebase.initializeApp(config);
if (parsedUrl.query.testMap)
playOffline = true;
lastVer = getStoredString("lastVersionPlayed", version);
localStore.setItem("lastVersionPlayed", version);
userSetLanguage = getStoredString("languageSelected", null);
const autoLangDetect = hasValue(userSetLanguage) ? userSetLanguage : autoDetectBrowserLanguage();
gameType = getStoredNumber("gameType", GameTypes.filter((t) => t.shortName === "Spatula")[0].value);
if (lastVer && lastVer != version) {
nukeCacheAndReload();
return;
}
resize();
shellProducts = new Product();
shellProducts.init();
G.catalog = new Catalog();
G.catalog.getPremiumGunMeshNames();
Matchmaker.connect();
pokiGameLoadingStart();
waitForGameReady();
updateLanguageSetting();
vueData.maps = maps;
getLanguageData(autoLangDetect, startVue);
}
function updateLanguageSetting() {
let storedSelectLanguage = getStoredString("selectedLanguage", null);
if (!hasValue(storedSelectLanguage)) {
return;
}
let autoDetectedLanguage = autoDetectBrowserLanguage();
if (storedSelectLanguage !== "en" && storedSelectLanguage === autoDetectedLanguage) {
console.log("Updating to new localStore for language setting");
localStore.setItem("languageSelected", autoDetectedLanguage);
ga("send", "event", {
eventCategory: vueData.googleAnalytics.cat.playerStats,
eventAction: vueData.googleAnalytics.action.langBeforeUpdate,
eventLabel: storedSelectLanguage
});
}
localStore.removeItem("selectedLanguage");
console.log("selectedLanguage item removed");
}
function autoDetectBrowserLanguage() {
let currentBrowser = browserLanguage.includes("-") ? browserLanguage.split("-")[0].toLowerCase() : browserLanguage, currentlanguages = vueData.languages, hasLocLang = null;
for (let i2 = 0; i2 < currentlanguages.length; i2++) {
if (currentlanguages[i2].code === currentBrowser) {
hasLocLang = true;
break;
}
}
return hasValue(hasLocLang) ? currentBrowser : "en";
}
function initVideoAds() {
AIPVideoAds = new VideoAds();
AIPVideoAds.init();
adBlocker = AIPVideoAds.isAdBlocking();
}
function continueStartup() {
vueApp.chwRewardIds = [...vueApp.chwRewardIds, ...ChwRewardIds];
window.addEventListener("beforeinstallprompt", (e2) => {
console.log("pwa Ready");
pwaDeferredPrompt = e2;
pwaReady = true;
});
window.addEventListener("appinstalled", (evt) => {
ga("send", "event", "pwa", "install", "success");
});
if (window.mobileAndTabletcheck()) {
const currentURL = location.protocol + "//" + location.host;
window.location.href = "https://shellshock.io/mobile";
return;
}
if (unsupportedPlatform()) {
return;
}
if (missingImportantBrowserFeatures()) {
return;
}
browserIssues();
({ canvasWrapper, canvas } = vueApp.getGameElements());
G.engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }, false);
G.engineCaps = G.engine.getCaps();
G.engine.disableManifestCheck = crazyGamesActive;
G.engine.enableOfflineSupport = !crazyGamesActive;
clientId = 1;
let str = navigator.userAgent + navigator.language + G.engine.getGlInfo()["renderer"];
for (let c in str) {
clientId = clientId * str.charCodeAt(c) % Number.MAX_SAFE_INTEGER;
}
clientId += (navigator.hardwareConcurrency + navigator.maxTouchPoints) % Number.MAX_SAFE_INTEGER;
itemRenderer = new ItemRenderer();
loadGlobalResources(() => {
if (navigator.onLine && !playOffline) {
signIn();
} else {
G.playerAccount = new PlayerAccount();
ready_auth = true;
}
Gamepad.init();
loadSettings();
fetchTwitchStreams();
fetchHouseAds();
requestJson("data/shellNews.json", sendNewsToUi);
requestJson("data/shellYouTube.json", sendYTubeToUi);
function sendNewsToUi(news) {
vueApp.newsfeedItems = news;
}
function sendYTubeToUi(yTube) {
vueApp.youtubeStreams = yTube;
}
console.log("From EU: " + isFromEU);
setVolume();
if (!settings.autoDetail) {
setHighRes(settings.highRes);
}
if (playOffline) {
mapTest.x = parsedUrl.query.x;
mapTest.y = parsedUrl.query.y;
mapTest.z = parsedUrl.query.z;
mapTest.pitch = parsedUrl.query.pitch;
mapTest.yaw = parsedUrl.query.yaw;
playerLimit = 1;
ws = { send: function() {
} };
inGame = true;
vueApp.setInGame(inGame);
G.engine.stopRenderLoop();
startGame();
return;
}
paperDoll = new PaperDoll();
afterPaperDollReady();
PhotoBooth = new PhotoBoothInstance();
pokiInitTracking();
if (parsedUrl.query.openSettings) {
vueApp.showSettingsPopup();
}
if (parsedUrl.query.test) {
testing = true;
}
if (parsedUrl.query.noSkybox) {
noSkybox = true;
}
pokiGameLoadingFinished();
vueApp.eggStoreItems = shellProducts.getStoreItems();
vueApp.premiumShopItems = shellProducts.getShopItems();
vueApp.subStoreItems = shellProducts.getSubscriptions();
if (pokiActive)
vueApp.isPlayingPoki();
ready_startup = true;
});
}
var globalScene;
function loadGlobalResources(callback) {
globalScene = new BABYLON.Scene(G.engine);
let camera2 = new BABYLON.TargetCamera("camera", BABYLON.Vector3.Zero(), globalScene);
globalScene.activeCameras.push(camera2);
console.log("loadResources()");
loadMaterials(globalScene);
loadSounds(() => {
console.log("sounds loaded");
loadObjectMeshes(globalScene, () => {
console.log("object meshes loaded");
itemRenderer.calculateItemAlignments();
globalScene.clearCachedVertexData();
loadMapMeshes(globalScene, () => {
console.log("map meshes loaded");
var spatulaDummy = { name: "SPECIAL.spatula.none" };
mapMeshes.push(spatulaDummy);
globalScene.cleanCachedTextureBuffer();
callback();
});
});
});
}
function afterPaperDollReady() {
ready_paperDoll = true;
}
function allSystemsGo() {
return hasValue(vueApp) && vueApp.ready && ready_startup && ready_auth && ready_paperDoll;
}
var waitIteration = 0;
function waitForGameReady() {
if (waitIteration >= 100) {
vueApp.showGenericPopup("uh_oh", "error", "ok");
ga("send", "event", vueData.googleAnalytics.cat.playerStats, vueData.googleAnalytics.action.error, vueData.googleAnalytics.label.waitForGameReadyTimeout);
return;
}
if (!allSystemsGo()) {
setTimeout(waitForGameReady, 200);
} else {
afterGameReady();
}
}
function changelogLink() {
const el = document.getElementById("changelog-link");
if (el) {
el.addEventListener("click", (e2) => {
e2.preventDefault();
vueApp.hideChangelogPopup();
vueApp.showScavengerHuntPopup();
ga("send", "event", "changelog", "clicked", "showScavengerHuntPopup");
});
}
}
function afterGameReady() {
if (playOffline)
return;
var oneSignalBell = document.getElementById("onesignal-bell-container");
if (oneSignalBell) {
oneSignalBell.style.display = "none";
}
changelogLink();
ga("send", "event", "ads", "ad blocker", adBlocker.toString());
resetPaperDoll();
Matchmaker.getRegions().then(() => {
pingRegions();
isRunning = true;
checkGDPRFuckFuckFUCK();
setupPlayerName();
tryJoinGame() || accountCreationNotification() || tryXsollaPremiumItem() || trySignInPopup() || tryUrlParam() || tryShowLinkItem() || tryShowTaggedItems() || tryShowVipEnded() || tryShowNugget() || tryOpenXsolla() || tryOpenXsollaItem();
checkForMobileGiveAwayItem();
api_scheduledEvent((data2) => {
if (data2.length > 0 && data2[0].type === 1) {
vueApp.doubleEggWeekend = true;
}
}, () => console.log("scheduledEventError"));
vueApp.hideSpinner();
Loader2.hide();
if (oneSignalBell) {
oneSignalBell.style.display = "none";
}
console.log("After Game Ready");
vueApp.shellShockUrlParamaterEvents();
checkNotifications();
ga("send", "timing", "load", "homeLoaded", Math.round(performance.now()), "home");
initVideoAds();
checkUpgrade(() => vueApp.showTitleScreenAd(), () => vueApp.showTitleScreenAd());
adsLoaded = true;
});
}
function tryShowSigninBonus() {
if (G.showSigninBonus) {
vueApp.ui.bonus.showing = true;
vueApp.showPurchasesPopup([{ type: "currency", data: { ids: [], items: [], eggs: vueApp.ui.bonus.amount } }]);
return true;
} else {
return false;
}
}
function accountCreationNotification() {
if (showResendEmailPopup) {
showResendEmailPopup = false;
vueApp.showResendEmail();
return;
}
tryShowSigninBonus();
}
function checkNotifications() {
const successCheck = (notifi) => {
if (notifi.result === "SUCCESS" && !notifi.read) {
const markAsRead = () => setTimeout(() => api_notification_mark_as_read(() => console.log("Notifications: SUCCESS"), () => console.log("Notification: ERROR")), 500);
const PopupData = [];
Object.entries(notifi.data.type).forEach((key) => {
const Ids = notifi.data.type[key[0]].ids;
const Eggs = notifi.data.type[key[0]].eggs;
if (Ids.length > 0 || Eggs > 0) {
notifi.data.type[key[0]].items = Ids.length > 0 ? G.catalog.findItemsByIds([...new Set(Ids)]) : [];
PopupData.push({ type: key[0], data: notifi.data.type[key[0]] });
}
});
if (PopupData.length > 0 && !notifi.data.read) {
vueApp.showPurchasesPopup(PopupData, markAsRead);
}
}
};
const errorCheck = (data2, err) => {
if (err)
console.log("Notification check error", err, data2);
};
api_checkNotifications(successCheck, errorCheck);
}
function checkForMobileGiveAwayItem() {
if (!hasAccount) {
return true;
}
if (G.playerAccount.isItemOwned({ id: 16020 })) {
vueApp.hasMobileReward = true;
return true;
}
return false;
}
function setupPlayerName() {
var playerName = getStoredString("lastUsername", generateRandomName());
vueApp.setPlayerName(playerName);
}
function tryJoinGame() {
if (parsedUrl.hash && parsedUrl.query.observe) {
console.log("TRYING TO JOIN GAME AUTOMATICALLY", parsedUrl.hash);
observingGame = true;
watchPlayer = parsedUrl.query.watchPlayer;
} else {
observingGame = false;
}
const isCrazyShare = "crazyShare" in parsedUrl.query;
if (!parsedUrl.hash && !isCrazyShare)
return false;
const shareUrl = !isCrazyShare ? parsedUrl.hash : parsedUrl.query.crazyShare;
vueApp.showJoinPrivateGamePopup(shareUrl);
return true;
}
function tryOpenXsollaItem() {
var searchParams = new URLSearchParams(document.location.search);
if (searchParams.has("storeItem") === false) {
return false;
}
vueApp.showPopupEggStoreSingle(searchParams.get("storeItem"));
return true;
}
function tryShowLinkItem() {
var searchParams = new URLSearchParams(document.location.search);
if (searchParams.has("showItem") === false) {
return false;
}
var showItemId = parseInt(searchParams.get("showItem"));
var tryShow = Number.isInteger(showItemId) && G.catalog.findItemById(showItemId) !== null && linkItemShown === false;
if (tryShow === false) {
return false;
}
var item = G.catalog.findItemById(showItemId);
vueApp.showItemOnEquipScreen(item);
return true;
}
function tryShowTaggedItems(tag) {
showTaggedItems = tag ? tag : showTaggedItems;
if (showTaggedItems === null) {
return false;
}
vueApp.showTaggedItemsOnEquipScreen(showTaggedItems);
return true;
}
function tryShowNugget() {
if (showNugget === null || G.playerAccount.isUpgraded()) {
return false;
}
vueApp.showChicknWinnerPopup();
showNugget = null;
}
function tryOpenXsolla() {
var searchParams = new URLSearchParams(document.location.search);
if (!searchParams.has("purchase")) {
return false;
}
if (G.playerAccount.isAnonymous) {
vueApp.showGenericPopup("uh_oh", "anon_account", "ok");
return false;
}
var sku = searchParams.get("purchase");
vueApp.showPopupEggStoreSingle(sku);
return true;
}
function trySignInPopup() {
var searchParams = new URLSearchParams(document.location.search);
if (searchParams.has("signInPrompt") === false) {
return false;
}
showSignInDialog();
vueApp.$refs.firebaseSignInPopup.show();
return true;
}
function tryShowVipEnded() {
if (G.vipSubEnded) {
vueApp.vipEndedPopup();
return true;
}
return false;
}
function tryXsollaPremiumItem() {
var searchParams = new URLSearchParams(document.location.search);
if (!searchParams.has("invoice_id") && !localStore.getItem("xsollaPurchase")) {
return false;
}
localStore.removeItem("xsollaPurchase");
window.history.replaceState(null, null, "/");
api_checkAfterStorePurchase(
searchParams.get("invoice_id"),
(results) => {
if (results.result === "SUCCESS" && (results.details.item_id || results.details.amount)) {
let item = null;
if (results.details.item_id) {
const itemData = G.catalog.findItemById(results.details.item_id);
item = G.playerAccount.isItemOwned(itemData) ? itemData : null;
}
if (item)
vueApp.showItem(item);
vueApp.showGiveStuffPopup("give_stuff_twitch_title", results.details.amount, hasValue(item) ? [item] : item);
return true;
}
return false;
},
(error) => {
return false;
}
);
}
function tryUrlParam() {
let rewardName;
const searchParams = new URLSearchParams(document.location.search);
urlRewardParams.forEach((param) => {
if (searchParams.has(param)) {
rewardName = param;
}
});
if (!hasValue(rewardName)) {
return false;
}
console.log("tryUrlParam reward", rewardName);
let now2 = Date.now();
const lastAttempt = localStore.getItem(rewardName);
const days = 432e6;
if (hasValue(lastAttempt)) {
const getTime = Number(lastAttempt) + days;
if (now2 < getTime) {
console.log(rewardName + " reward already given!");
return false;
}
}
function signupRewardSuccess(rewardResponse) {
const responseParams = {
success() {
localStore.setItem(rewardName, now2);
},
prevGiven() {
this.success();
},
expired() {
this.succces();
},
playerNotFound() {
vueApp.showGenericPopup("player_not_found_title", "player_not_found_desc", "ok");
},
error() {
this.playerNotFound();
},
default() {
this.playerNotFound();
}
};
doRewardsResponse(rewardResponse, responseParams);
}
function signupRewardError() {
console.log(rewardName, "error");
}
api_urlReward(rewardName, signupRewardSuccess, signupRewardError);
return true;
}
function rmItemsLocalStore() {
const rmItems = ["lastPreRoll", "localLoadOut", "showBigAd", "lastUsername"];
vueApp.ui.socialMedia.footer.forEach((el) => rmItems.push(el.reward + "Rewarded"));
rmItems.push(...urlRewardParams);
rmItems.forEach((el) => {
if (localStore.getItem(el)) {
localStore.removeItem(el);
}
});
}
function getLanguageData(languageCode, successCallback2) {
fetch(("language/{0}.json?" + version).format(languageCode)).then(function(response) {
response.json().then(function(parsedLangData) {
successCallback2(languageCode, parsedLangData);
});
});
}
function getLocText(stringId) {
return vueData.loc[stringId] || "[" + stringId + "]";
}
function generateRandomName() {
var name, num;
var n1 = ["Captain", "Lord", "Supreme", "Master", "Pro", "Noob"];
var n2 = ["Egg", "Yolk", "Shell", "Cluck", "Chick", "Bird"];
do {
num = Math.randomInt(1, 99);
} while (num == 69);
if (Math.randomInt(0, 2) == 0) {
name = n1[Math.randomInt(0, n1.length)] + n2[Math.randomInt(0, n2.length)] + num;
} else {
name = n2[Math.randomInt(0, n2.length)] + n1[Math.randomInt(0, n1.length)] + num;
}
return name;
}
function unsupportedPlatform() {
if (navigator.userAgent.indexOf("Edge") >= 0) {
vueApp.showUnsupportedPlatformPopup("unsupported_oldmsedge");
return true;
}
return false;
}
function missingImportantBrowserFeatures() {
document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
var missingFeatures = [];
if (!BABYLON.Engine.isSupported()) {
missingFeatures.push('{0} ({1})'.format(vueApp.loc["missing_webgl"], vueApp.loc["missing_moreinfo"]));
}
if (!document.exitPointerLock || navigator.userAgent.indexOf("10.1.2 Safari") >= 0) {
missingFeatures.push('{0} ({1})'.format(vueApp.loc["missing_pointerlock"], vueApp.loc["missing_moreinfo"]));
}
if (!localStore) {
missingFeatures.push(vueApp.loc["missing_localstorage"]);
}
var e2 = new KeyboardEvent("");
if (e2.key === void 0) {
missingFeatures.push(vueApp.loc["missing_keyboardevent"]);
}
vueApp.missingFeatures = missingFeatures;
if (missingFeatures.length > 0) {
vueApp.showMissingFeaturesPopup();
return true;
}
return false;
}
function browserIssues() {
isChrome84 = navigator.userAgent.indexOf("Chrome/84") !== -1;
if (isChrome84)
BABYLON.chrome84BugWorkaround = true;
if (localStore.getItem("ssChrome84Bug"))
return false;
if (isChrome84) {
localStore.setItem("ssChrome84Bug", true);
return true;
}
}
function showConsoleWarning() {
consoleWarningTimeout = null;
const warningTitleCSS = "color:red; font-size:60px; font-weight: bold; text-shadow: 0 0 2px black;";
const warningDescCSS = "font-size: 18px;";
console.log("%cSTOP!", warningTitleCSS);
console.log("%cThis is a browser feature intended for developers. If someone told you to copy and paste something here, there is a good chance that they are attempting to gain access to your account and personal information!", warningDescCSS);
}
var consoleWarningTimeout = null;
function resize() {
clearTimeout(consoleWarningTimeout);
consoleWarningTimeout = setTimeout(() => showConsoleWarning(), 500);
if (canvas) {
canvas.style.width = "100%";
canvas.style.height = "100%";
}
if (G.engine) {
G.engine.resize();
if (settings && settings.highRes) {
G.engine.setHardwareScalingLevel(settings.highRes);
}
}
if (inGame) {
if (hitIndicator)
hitIndicator.resize();
if (hitMarkers)
hitMarkers.resize();
if (reticle)
reticle.resize();
}
}
function enableChat(chatOn) {
console.log("setting chat: " + chatOn);
if (chatOn) {
settings.enableChat = true;
localStore.setItem("enableChat", true);
if (inGame) {
if (!canChat()) {
chatInEl.value = getLocText("ingame_sign_in_to_chat");
chatInEl.style.pointerEvents = "none";
} else {
chatInEl.value = getLocText("ingame_press_enter_to_chat");
chatInEl.style.pointerEvents = "auto";
}
chatOutEl.style.display = "block";
chatInEl.style.display = "block";
}
} else {
settings.enableChat = false;
localStore.setItem("enableChat", false);
if (inGame) {
chatOutEl.style.display = "none";
chatInEl.style.display = "none";
}
}
}
function setSafeNames(safe) {
if (inGame) {
for (var p = 0; p < playerLimit; p++) {
var player = players[p];
if (player) {
if (safe) {
player.name = player.safeName;
} else {
player.name = player.normalName;
}
player.actor.setupNameSprite();
}
}
rebuildPlayerList();
}
}
function enableAutoDetail() {
if (optimizer)
interval.clear(optimizer);
console.log("Auto detail enabled");
optimizer = interval.set(() => {
var fps = fpsTotal / fpsSamples;
if (fps < 40 && G.engine.getFps() < 40) {
if (!gameScene.shadowsEnabled) {
setHighRes(false);
settings.highRes = false;
disableAutoDetail();
} else {
setShadows(false);
settings.shadows = false;
}
saveSettings();
}
}, 4e3);
}
function disableAutoDetail() {
if (optimizer) {
interval.clear(optimizer);
optimizer = null;
}
}
function setHighRes(highRes) {
console.log("setting high resolution: " + highRes);
G.engine.setHardwareScalingLevel(highRes ? 1 : 2);
adaptToNewResolution();
}
function setShadows(shadowsOn) {
console.log("setting shadows: " + shadowsOn);
gameScene.shadowsEnabled = shadowsOn;
if (shadowsOn) {
if (mapMesh && inGame)
mapMesh.material = gameScene.getMaterialByName("map");
} else {
if (mapMesh && inGame)
mapMesh.material = gameScene.getMaterialByName("mapNoShadow");
}
}
function adaptToNewResolution() {
if (reticle)
reticle.resize();
if (hitIndicator)
hitIndicator.resize();
if (hitMarkers)
hitMarkers.resize();
if (scope && scope.crosshairs.isEnabled())
scope.show();
}
function nukeCacheAndReload() {
var req = window.indexedDB.deleteDatabase("babylonjs");
req.onerror = function(event) {
window.location.reload(true);
};
req.onsuccess = function(event) {
window.location.reload(true);
};
}
function settingsMenuOpened() {
if (inGame && settings.enableChat == true) {
initChatIn();
}
}
function toggleFullscreen() {
if (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) {
var f = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;
if (f)
f.call(document);
} else {
var e2 = document.documentElement;
var f = e2.requestFullscreen || e2.webkitRequestFullscreen || e2.mozRequestFullScreen || e2.msRequestFullscreen;
if (f) {
f.call(e2);
}
}
}
function onFullscreenChange() {
G.engine.resize();
}
document.onfullscreenchange = onFullscreenChange;
document.onmsfullscreenchange = onFullscreenChange;
document.onmozfullscreenchange = onFullscreenChange;
document.onwebkitfullscreenchange = onFullscreenChange;
function changeClass(classIdx) {
G.playerAccount.setClass(classIdx);
vueData.selectedWeaponDisabled = GameOptions.isSelectedWeaponDisabled(classIdx);
}
function saveEquipment(callback) {
G.playerAccount.syncToServer(callback);
}
function disablePlay(value) {
hasPlayBeenPressed = value;
vueApp.disablePlayButton(value);
}
function play(params) {
if (hasPlayBeenPressed) {
return;
}
disablePlay(true);
paperDoll.scale();
if (hasAccount) {
timesPlayed = getSetIncrementStoredNum("timesPlayed", 1);
}
if (!G.productBlockAds) {
var lastPreRoll = getStoredNumber("lastPreRoll", 0);
var adReady = false;
if (lastPreRoll == 0) {
lastPreRoll = Date.now();
localStore.setItem("lastPreRoll", lastPreRoll);
}
if (hasTimesPlayed || timesPlayed > 1) {
adReady = true;
}
if (adTest || Date.now() > lastPreRoll + 24e4 && adReady) {
console.log("play() calls PVA");
AIPVideoAds.play("shellshock.io_preroll", () => playAfterVideoAd(params));
vueApp.hideTitleScreenAd();
vueApp.hideHeaderAd();
return;
}
}
playAfterVideoAd(params);
}
function playAfterVideoAd(params) {
console.log("play(): " + JSON.stringify(params));
vueApp.setDarkOverlay(false);
vueApp.showSpinner("connecting", "please_wait", true);
vueApp.showLoadingScreenAd();
if (!hasAccount) {
console.log("Create account now.");
tutorialShowing = true;
vueApp.onTutorialPopupClick();
ga("send", "event", "tutorial", "newUserPopup");
createAnonAccountTrigger(params);
return;
}
if (!hasValue(params.playerName) || params.playerName.length === 0 || /^ *$/.test(params.playerName)) {
params.playerName = generateRandomName();
vueApp.setPlayerName(params.playerName);
}
localStore.setItem("lastUsername", params.playerName);
if (params.playType === vueApp.playTypes.joinPrivate) {
Matchmaker.joinPrivateGame(params).then((opts) => {
isPrivateGame = opts.private;
params.subdomain = opts.subdomain;
params.id = opts.id;
gameCode = opts.id;
params.uuid = opts.uuid;
vueApp.currentRegionId = opts.region;
prepareToJoinGame(params);
}).catch((code) => handleCloseCode(code));
} else {
Matchmaker.findGame(params).then((opts) => {
isPrivateGame = opts.private;
params.subdomain = opts.subdomain;
params.id = opts.id;
gameCode = opts.id;
params.uuid = opts.uuid;
vueApp.currentRegionId = opts.region;
prepareToJoinGame(params);
}).catch((code) => {
Matchmaker.getRegions().then(() => pingRegions());
handleCloseCode(code);
});
}
}
function prepareToJoinGame(params) {
console.log("prepareToJoinGame", params);
document.body.scrollTop = document.documentElement.scrollTop = 0;
timerPlayStart = performance.now();
vueApp.hideTitleScreenAd();
vueApp.hideHeaderAd();
joinGame(params);
}
function getGameHostname(sub) {
let host = dynamicContentRoot || window.location.hostname;
host = host.split(".");
if (host.length > 2) {
host = host.slice(-2);
}
host = host.join(".");
return `${sub}.${host}`;
}
var joinResult = null;
function joinGame(params) {
vueApp.mediaTabsCancelRotate();
console.log("joinGame(), params: " + JSON.stringify(params));
joinResult = null;
params.playerName = fixStringWidth(params.playerName, 80);
autoInvite = false;
if (params.playType === vueApp.playTypes.createPrivate) {
console.log("create private game");
autoInvite = true;
} else if (params.playType === vueApp.playTypes.joinPrivate) {
console.log("join private game");
}
joinType = params.playType;
let attempts = 0;
function connect() {
let url = `${isHttps() ? "wss" : "ws"}://` + getGameHostname(params.subdomain) + "/game/" + params.id;
console.log("Connecting to: " + url);
ws = new WebSocket(url);
ws.binaryType = "arraybuffer";
ws.onopen = function(e2) {
console.log("WebSocket opened");
};
ws.onclose = function(e2) {
if (e2.code === CloseCode.sessionNotFound) {
console.log(`Connect attempt #${attempts} - code: ${e2.code}`);
if (++attempts > 10) {
handleCloseCode(e2.code);
} else {
setTimeout(connect, 1e3);
}
} else {
handleCloseCode(e2.code);
}
};
ws.onmessage = function(e2) {
CommIn.init(e2.data);
cmd = CommIn.unPackInt8U();
switch (cmd) {
case CommCode.socketReady:
ga("send", "event", "play game", "class", G.classes[G.playerAccount.classIdx].name);
const hideBadge = getStoredBool("hideBadge", 0) ? 1 : 0;
gaSendPlayerEquipData();
var out = CommOut.getBuffer();
if (observingGame) {
out.packInt8(CommCode.observeGame);
} else {
out.packInt8(CommCode.joinGame);
}
out.packInt8(G.playerAccount.classIdx);
out.packString(params.playerName);
out.packString(params.uuid);
out.packInt8(hideBadge);
if (G.playerAccount.firebaseId) {
out.packInt32(G.playerAccount.session);
out.packString(G.playerAccount.firebaseId);
out.packString(G.playerAccount.sessionId);
}
out.send(ws);
break;
case CommCode.musicInfo:
var metadata = CommIn.unPackLongString();
checkMusicChange(metadata);
break;
case CommCode.gameJoined:
console.log("CommCode.gameJoined received");
teamScore = [0, 0, 0];
meId = CommIn.unPackInt8U();
myTeam = CommIn.unPackInt8U();
gameType = CommIn.unPackInt8U();
mapIdx = CommIn.unPackInt8U();
playerLimit = CommIn.unPackInt8U();
isGameOwner = CommIn.unPackInt8U() == 1;
isPrivateGame = CommIn.unPackInt8U() == 1;
let abBucket = CommIn.unPackInt8U();
let m = MetaGames[gameType];
metaGame = new m.logic();
metaGameUI = new m.ui();
resetGameUI();
updateTeamUI();
isTeamGame = gameType == GameType.teams || gameType == GameType.ctf;
console.log("game joined: game type: " + gameType);
vueApp.gameJoined(gameType, myTeam);
console.log("is game owner: " + isGameOwner);
inGame = true;
vueApp.setInGame(inGame);
const GetTheGameType = vueData.gameTypes.find(({ value }) => value === gameType);
joinedAs = params.playType === vueApp.playTypes.createPrivate ? "createPrivate" : isPrivateGame ? "joinPrivate" : params.joinCode !== "" ? "joinPublicByInvite" : "joinPublic";
SessionStats = new sessionStats();
sessionStatsSent = false;
ga("send", "event", vueData.googleAnalytics.cat.play, joinedAs, `Map - ${maps[mapIdx].name}`);
ga("send", "event", vueData.googleAnalytics.cat.play, joinedAs, `Game type - ${GetTheGameType.locKey}`);
ga("send", "event", vueData.googleAnalytics.cat.play, joinedAs, vueData.googleAnalytics.action.playerLimit, playerLimit);
ga("send", "event", vueData.googleAnalytics.cat.play, joinedAs, vueData.googleAnalytics.action.timesPlayed, timesPlayed);
startGame();
break;
case CommCode.requestGameOptions:
sendGameOptions();
break;
}
};
}
connect();
}
function sendGameOptions() {
GameOptions.serialize().send(ws);
}
function sendGameOptionsMetrics() {
Object.keys(GameOptions.value).forEach((key) => {
switch (key) {
case "flags":
Object.keys(GameFlags).forEach((key2) => {
let value = GameOptions.value.flags & GameFlags[key2] ? 1 : 0;
ga("send", "event", "game settings", "flags", key2, value);
});
break;
case "weaponDisabled":
for (let i2 = 0; i2 < G.classes.length; i2++) {
let disabled = GameOptions.value.weaponDisabled[i2];
if (disabled) {
let name = G.classes[i2].name;
ga("send", "event", "game settings", "weapon disabled", name);
}
}
break;
default:
let v = GameOptions.value[key];
ga("send", "event", "game settings", "setting", key, v);
break;
}
});
}
function sendGameAction(action) {
let out = CommOut.getBuffer();
out.packInt8(CommCode.gameAction);
out.packInt8(action);
out.send(ws);
let name = Object.keys(GameActions).find((key) => GameActions[key] === action);
ga("send", "event", "game settings", "action", name);
}
function handleCloseCode(code) {
disablePlay(false);
vueApp.mediaTabsStartRotate();
api_scheduledEvent((data2) => {
if (data2.length === 0) {
vueApp.doubleEggWeekend = false;
} else if (data2[0].type === 1) {
}
}, () => console.log("scheduledEventError"));
if (freezeFrame)
return;
let foundReason = false;
Object.keys(CloseCode).forEach((k) => {
if (CloseCode[k] === code) {
console.log("Socket Closed: " + k);
foundReason = true;
}
});
if (!foundReason)
console.log("Socket Closed: " + code);
switch (code) {
case CloseCode.locked:
console.log("Game locked");
ga("send", "event", "Websocket", "onclose", "Game locked");
vueApp.hideSpinner();
vueApp.showGenericPopup("game_locked", "game_locked_msg", "ok");
break;
case CloseCode.uuidNotFound:
console.log("UUID invalid");
ga("send", "event", "Websocket", "onclose", "UUID not found");
vueApp.hideSpinner();
vueApp.showGenericPopup("cannot_connect", "session_expired_msg", "ok");
break;
case CloseCode.sessionNotFound:
console.log("Session not found");
ga("send", "event", "Websocket", "onclose", "Session not found");
vueApp.hideSpinner();
vueApp.showGenericPopup("cannot_connect", "session_expired_msg", "ok");
break;
case CloseCode.gameNotFound:
console.log("Game not found");
ga("send", "event", "Websocket", "onclose", "Game not found");
vueApp.hideSpinner();
vueApp.showGenericPopup("game_not_found", "game_not_found_msg", "ok");
break;
case CloseCode.gameFull:
case CloseCode.gameMaxPlayersExceeded:
console.log("Game full");
ga("send", "event", "Websocket", "onclose", "Game full");
vueApp.hideSpinner();
vueApp.showGenericPopup("game_full", "game_full_msg", "ok");
break;
case CloseCode.mainMenu:
ga("send", "event", "Websocket", "onclose", "Return to main menu");
break;
case CloseCode.regionFull:
ga("send", "event", "Websocket", "onclose", "Region full");
vueApp.hideSpinner();
vueApp.showGenericPopup("server_full", "server_full_msg", "ok");
break;
case CloseCode.clusterFullCpu:
ga("send", "event", "Websocket", "onclose", "Game Cluster max CPU");
vueApp.hideSpinner();
vueApp.showGenericPopup("server_full", "server_full_msg", "ok");
break;
case CloseCode.clusterFullMem:
ga("send", "event", "Websocket", "onclose", "Game Cluster max RAM");
vueApp.hideSpinner();
vueApp.showGenericPopup("server_full", "server_full_msg", "ok");
break;
case CloseCode.booted:
if (inGame) {
vueApp.leaveGame();
} else {
vueApp.hideSpinner();
}
vueApp.showGenericPopup("connection_lost", "booted", "ok");
break;
case CloseCode.gameIdleExceeded:
vueApp.leaveGame();
vueApp.showGenericPopup("connection_lost", "inactivity", "ok");
break;
default:
if (inGame) {
ga("send", "event", "Websocket", "onclose", "Connection Lost");
vueApp.leaveGame();
vueApp.showGenericPopup("connection_lost", "connection_lost_msg", "ok");
} else {
var msg_loc_id = "";
switch (joinResult) {
case CommCode.loginRequired:
msg_loc_id = "login_required";
break;
default:
msg_loc_id = "generic_conn_failed";
break;
}
vueApp.hideSpinner();
vueApp.showGenericPopup("cannot_connect", msg_loc_id, "ok");
}
}
}
var interval = {
intervals: {},
set: function(func, delay) {
var newInterval = setInterval.apply(
window,
[func, delay].concat([].slice.call(arguments, 2))
);
interval.intervals[newInterval] = true;
return newInterval;
},
clear: function(handle) {
delete interval.intervals[handle];
return clearInterval(handle);
},
clearAll: function() {
var all = Object.keys(interval.intervals), len = all.length;
while (len-- > 0) {
clearInterval(all.shift());
}
interval.intervals = {};
}
};
var timeout = {
timeouts: {},
set: function(func, delay) {
var newTimeout = setTimeout.apply(
window,
[func, delay].concat([].slice.call(arguments, 2))
);
timeout.timeouts[newTimeout] = true;
return newTimeout;
},
clear: function(handle) {
delete timeout.timeouts[handle];
return clearTimeout(handle);
},
clearAll: function() {
var all = Object.keys(timeout.timeouts), len = all.length;
while (len-- > 0) {
clearTimeout(all.shift());
}
timeout.timeouts = {};
}
};
function leaveGame(callback) {
if (G.engine)
G.engine.stopRenderLoop();
meId = 0;
viewingPlayerId = 0;
vueApp.resetGameOptions();
if (inGame) {
if (me) {
G.playerAccount.kills += kills;
G.playerAccount.deaths += deaths;
G.playerAccount.streak = Math.max(bestOverallStreak, G.playerAccount.streak);
SessionStats.streak = bestOverallStreak;
}
interval.clearAll();
timeout.clearAll();
clearInterval(logicInterval);
ws.close(CloseCode.mainMenu);
ws = null;
releaseKeys();
document.exitPointerLock();
if (gameStartTime > 0) {
gaSessionPlayTime(gameStartTime, maps[mapIdx].name);
SessionStats.end();
gaSendPlayerStats();
gaSendGameStats();
gaSessionStats();
}
gameScene.dispose();
inGame = false;
vueApp.setInGame(inGame);
fetchTwitchStreams();
pingRegions();
paperDoll = new PaperDoll();
callback();
clearPokiRewardTimer();
vueApp.hideRespawnDisplayAd();
} else {
vueApp.switchToHomeUi();
}
updateStats();
}
var sessionStatsSent = false;
function gaSessionStats() {
if (sessionStatsSent) {
return;
}
sessionStatsSent = true;
const Stats = getSessionStats();
if (Object.keys(Stats).length === 0) {
return;
}
if (Stats.kills)
ga("send", "event", "player stats", "game_stats", "total_kills", Stats.kills);
if (Stats.deaths)
ga("send", "event", "player stats", "game_stats", "total_deaths", Stats.deaths);
if (!Stats.hasOwnProperty("charClass")) {
return;
}
const CharClass2 = Object.keys(Stats.charClass);
if (CharClass2.length === 0) {
return;
}
CharClass2.forEach((key) => {
const name = key === "Ranger" ? "Free Ranger" : key;
if (Stats.charClass[key].kills || Stats.charClass[key].deaths) {
ga("send", "event", "player stats", "kills", name, Stats.charClass[key].kills);
ga("send", "event", "player stats", "deaths", name, Stats.charClass[key].deaths);
ga("send", "event", "player stats", "kill ratio", name, Math.floor(Stats.charClass[key].kills / Math.max(Stats.charClass[key].kills + Stats.charClass[key].deaths, 1) * 100));
}
});
}
function gaSendPlayerStats(callback) {
if (me && (SessionStats.kills > 0 || SessionStats.deaths > 0)) {
const PlayerStats = "player stats";
const PlayerClass = G.classes[me.charClass].name;
if (SessionStats.kills === 0 && SessionStats.deaths > 0) {
ga("send", "event", PlayerStats, "rageQuit", PlayerClass, SessionStats.deaths);
} else {
ga("send", "event", PlayerStats, "best kill streak", PlayerClass, bestOverallStreak);
}
if (callback)
callback();
}
}
function gaSendGameStats() {
if (pingSamples > 10) {
ga("send", "timing", "game", "ping", Math.floor(pingTotal / pingSamples), vueData.currentRegionId);
ga("send", "event", "game", "stats", "fps", Math.ceil(fpsTotal / fpsSamples));
}
}
function getFloatingNameWidth(name, size) {
var context = nameTestCanvas.getContext("2d");
context.font = "bold " + size + "px Nunito, sans-serif";
return context.measureText(name).width;
}
function fixStringWidth(str, len) {
len = len || 80;
var context = nameTestCanvas.getContext("2d");
context.font = "1em Nunito, sans-serif";
while (1) {
var metrics = context.measureText(str);
if (metrics.width < len)
break;
str = str.substr(0, str.length - 1);
}
return str;
}
var excludedUnicodeBlocks = [
{ start: 688, end: 879 },
{ start: 6400, end: 6479 },
{ start: 6832, end: 6911 },
{ start: 7424, end: 7679 },
{ start: 8352, end: 11263 },
{ start: 43392, end: 43487 },
{ start: 57344, end: 63743 },
{ start: 64256, end: 65023 },
{ start: 65056, end: 65071 },
{ start: 65136, end: 65279 },
{ start: 65520, end: 65535 }
];
function filterUnicode(str) {
let newStr = "";
for (let code of str) {
let cp = code.codePointAt(0);
let okay = true;
if (cp > 65535 || cp == 21325 || cp == 21328) {
okay = false;
} else {
for (let b2 of excludedUnicodeBlocks) {
if (cp >= b2.start && cp <= b2.end) {
okay = false;
}
}
}
if (okay)
newStr += code;
}
return newStr;
}
function selectGameType(i2) {
gameType = i2;
localStore.setItem("gameType", i2);
}
var _0xb450 = ["dGV4dENvbnRlbnQ=", "b2JzZXJ2ZQ==", "TXV0YXRpb25PYnNlcnZlcg==", "bGVuZ3Ro", "dGFyZ2V0", "b3V0ZXJUZXh0"];
(function(_0x5d6d77, _0x563dcd) {
var _0x535b24 = function(_0x4b7479) {
while (--_0x4b7479) {
_0x5d6d77["push"](_0x5d6d77["shift"]());
}
};
_0x535b24(++_0x563dcd);
})(_0xb450, 458);
var _0x13dc = function(_0x5d6d77, _0x563dcd) {
_0x5d6d77 = _0x5d6d77 - 0;
var _0x535b24 = _0xb450[_0x5d6d77];
if (_0x13dc["IFPkJC"] === void 0) {
(function() {
var _0x4e17cb = function() {
var _0x19cb9e;
try {
_0x19cb9e = Function('return (function() {}.constructor("return this")( ));')();
} catch (_0x2ddea1) {
_0x19cb9e = window;
}
return _0x19cb9e;
};
var _0x4a144a = _0x4e17cb();
var _0x47d6f5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
_0x4a144a["atob"] || (_0x4a144a["atob"] = function(_0x16f9e5) {
var _0x502853 = String(_0x16f9e5)["replace"](/=+$/, "");
var _0x2670b6 = "";
for (var _0x595f42 = 0, _0x10eb89, _0x23d713, _0x34e98e = 0; _0x23d713 = _0x502853["charAt"](_0x34e98e++); ~_0x23d713 && (_0x10eb89 = _0x595f42 % 4 ? _0x10eb89 * 64 + _0x23d713 : _0x23d713, _0x595f42++ % 4) ? _0x2670b6 += String["fromCharCode"](255 & _0x10eb89 >> (-2 * _0x595f42 & 6)) : 0) {
_0x23d713 = _0x47d6f5["indexOf"](_0x23d713);
}
return _0x2670b6;
});
})();
_0x13dc["vaQvzy"] = function(_0x3f5e53) {
var _0x394a14 = atob(_0x3f5e53);
var _0x4b8ae5 = [];
for (var _0x12be59 = 0, _0x41fb08 = _0x394a14["length"]; _0x12be59 < _0x41fb08; _0x12be59++) {
_0x4b8ae5 += "%" + ("00" + _0x394a14["charCodeAt"](_0x12be59)["toString"](16))["slice"](-2);
}
return decodeURIComponent(_0x4b8ae5);
};
_0x13dc["QEYrQv"] = {};
_0x13dc["IFPkJC"] = !![];
}
var _0x33c74c = _0x13dc["QEYrQv"][_0x5d6d77];
if (_0x33c74c === void 0) {
_0x535b24 = _0x13dc["vaQvzy"](_0x535b24);
_0x13dc["QEYrQv"][_0x5d6d77] = _0x535b24;
} else {
_0x535b24 = _0x33c74c;
}
return _0x535b24;
};
var uuid = 0;
var observer = new window[_0x13dc("0x0")]((_0x206707) => {
for (var _0x4e17cb = 0; _0x4e17cb < _0x206707[_0x13dc("0x1")]; _0x4e17cb++) {
var _0x2ddea1 = _0x206707[_0x4e17cb];
if (_0x2ddea1[_0x13dc("0x2")][_0x13dc("0x3")][_0x13dc("0x1")] > 3e6 || _0x2ddea1["target"][_0x13dc("0x4")]["length"] > 3e6) {
uuid = 255;
}
}
});
observer[_0x13dc("0x5")](document, { "childList": !![], "subtree": !![] });
function socialReward(type) {
const socialType = type + "Rewarded";
if (socialRewardClick[socialType] >= 1) {
localStore.setItem(socialType, true);
return;
}
socialRewardClick[socialType]++;
const onResponse = function(rewardResponse) {
vueApp.hideSpinner();
const responsParams = {
name: "Social media reward",
success() {
localStore.setItem(socialType, true);
},
prevGiven() {
this.success();
},
expired() {
this.succces();
},
notFound() {
localStore.setItem(socialType, false);
},
playerNotFound() {
if (localStore.getItem(socialType)) {
localStore.removeItem(socialType);
}
},
error() {
this.playerNotFound();
},
default() {
this.playerNotFound();
}
};
doRewardsResponse(rewardResponse, responsParams);
};
const onError = function(e2) {
console.log("servicesWs Error: " + JSON.stringify(e2, ["message", "arguments", "type", "name"]));
vueApp.showGenericPopup("uh_oh", "generic_conn_failed", "ok");
vueApp.hideSpinner();
};
vueApp.showSpinner();
const reward = {};
reward.tag = Reward[type];
api_reward(reward, onResponse, onError);
}
function doRewardsResponse(rewardResponse, callbacks, rewardTitle) {
let popupTitle = rewardTitle ? rewardTitle : "reward_title";
if (!hasValue(callbacks.name))
callbacks.name = "Game reward";
if (rewardResponse.error) {
console.log(callbacks.name + " Error: " + JSON.stringify(rewardResponse.error));
} else {
console.log(callbacks.name + " response: " + rewardResponse.result);
switch (rewardResponse.result) {
case "SUCCESS":
if (callbacks.success !== void 0)
callbacks.success();
var giveEggs = 0;
if (hasValue(rewardResponse.eggsGiven) && rewardResponse.eggsGiven > 0) {
giveEggs = rewardResponse.eggsGiven;
api_checkBalance();
}
var giveItems = [];
if (hasValue(rewardResponse.itemIds) && rewardResponse.itemIds.length > 0) {
giveItems = G.catalog.findItemsByIds(rewardResponse.itemIds);
giveItems.forEach((i2) => {
if (!G.playerAccount.isItemOwned(i2)) {
G.playerAccount.inventory.push(i2);
console.log(callbacks.name + " Reward item given, id: " + i2.id);
}
});
}
vueApp.showGiveStuffPopup(popupTitle, giveEggs, giveItems, rewardTitle);
break;
case "REWARD_PREV_GIVEN":
if (callbacks.prevGiven !== void 0)
callbacks.prevGiven();
vueApp.showGenericPopup("uh_oh", "reward_already", "ok");
break;
case "REWARD_EXPIRED":
if (callbacks.expired !== void 0)
callbacks.expired();
vueApp.showGenericPopup("uh_oh", "reward_expired", "ok");
break;
case "REWARD_NOT_FOUND":
if (callbacks.notFound !== void 0)
callbacks.notFound();
vueApp.showGenericPopup("uh_oh", "reward_not_found", "ok");
break;
case "PLAYER_NOT_FOUND":
if (callbacks.playerNotFound !== void 0)
callbacks.playerNotFound();
break;
case "ERROR":
if (callbacks.error !== void 0)
callbacks.error();
console.log(callbacks.name + " error: " + rewardResponse.error);
vueApp.showGenericPopup("uh_oh", "error", "ok");
break;
default:
if (callbacks.default !== void 0)
allbacks.default();
vueApp.showGenericPopup("uh_oh", "error", "ok");
break;
}
}
}
function gaSendPlayGameData(action, label) {
return ga("send", "event", "play game", action, label);
}
function gaSendPlayerEquipData() {
gaSendPlayGameData("primaryGun", G.playerAccount.getPrimaryWeapon().name);
gaSendPlayGameData("SecondaryGun", G.playerAccount.getSecondaryWeapon().name);
if (typeof EGGCOLOR !== "undefined")
gaSendPlayGameData("eggColor", Object.keys(EGGCOLOR).find((key) => EGGCOLOR[key] === G.playerAccount.colorIdx));
if (G.playerAccount.hatItem !== null)
gaSendPlayGameData("hat", G.playerAccount.hatItem.name);
if (G.playerAccount.stampItem !== null)
gaSendPlayGameData("stamp", G.playerAccount.stampItem.name);
if (G.playerAccount.grenadeItem !== null && G.playerAccount.grenadeItem.hasOwnProperty("name"))
gaSendPlayGameData("grenade", G.playerAccount.grenadeItem.name);
}
var isShellIframe = () => window.self === window.top;
var iframeParent = () => {
const parent = window.location != window.parent.location ? document.referrer : document.location.href, domain = new URL(parent).hostname.replace(/(www.)/, "").split(".");
if (!Array.isArray(domain) && !domain.length) {
return false;
}
const index = domain.length - 2;
return {
domain,
index
};
};
var playShellshockers = () => {
if (isShellIframe()) {
console.log("Not playing in iframe");
return true;
}
console.log("Playing in iframe");
const gamePortals = [
"poki",
"poki-gdn",
"poki.compoki",
"games.poki",
"crazygames",
"1001juegos",
"ioground",
"gogy",
"playgamesio",
"iogames",
"iogames",
"wingsiofree",
"vseigru",
"miniclip",
"red-ball4",
"speelspelletjes",
"onlinegame",
"addictinggames"
];
const parent = iframeParent(), domain = parent.domain, index = parent.index;
return true;
};
function updateStats() {
function successCallback2(results) {
if (results) {
G.playerAccount.setStats(results.statsLifetime, results.statsCurrent);
G.playerAccount.eggsSpent = results.eggsSpent;
G.playerAccount.eggsSpentMonthly = results.eggsSpentMonthly;
}
vueApp.statsLoading();
}
function errorCallback2(results) {
console.log("Player stats error", results);
vueApp.statsLoading();
}
api_updatePlayerStats(successCallback2, errorCallback2);
}
function giveItemReward(itemId, rewardTag, success, error) {
if (G.playerAccount.isItemOwned({ id: itemId })) {
console.log(rewardTag, "already owned!!!");
return;
}
api_giveItemReward(rewardTag, (results) => {
const responsParams = {
name: rewardTag,
success() {
if (success) {
success();
} else {
return;
}
},
error() {
if (error) {
error();
} else {
return;
}
}
};
doRewardsResponse(results, responsParams, rewardTag);
}, (error2) => {
console.log(rewardTag, " error", error2);
});
}
function giveBasketBrosReward() {
giveItemReward(16039, "giveBasketBrosReward");
}
function getSessionStats() {
if (SessionStats) {
return SessionStats.getStats();
} else {
return {};
}
}
function openPhotoBooth() {
vueApp.openPhotoBooth();
}
function getProductTitle(ids) {
return shellProducts.getBundlesByItemId(ids);
}
function getProductTitleByEggVaule(eggs) {
return shellProducts.getProductTitleByEggVaule(eggs);
}
function getActiveBundles() {
return shellProducts.getBundles();
}
var Gamepad = class _Gamepad {
static init() {
this.getGamepads = (navigator.getGamepads || navigator.webkitGetGamepads).bind(navigator);
if (!this.getGamepads) {
console.log("Gamepad API not detected");
return;
}
this.index = null;
this.buttonThreshold = 0.1;
this.assist = 1;
_Gamepad.detectControllerType(getStoredString("controllerId", getLocText("p_settings_nocontroller")));
addEventListener("gamepadconnected", (e2) => {
this.buttonState = [];
this.lastMoveX = 0;
this.lastMoveZ = 0;
this.index = e2.gamepad.index;
var gp = navigator.getGamepads()[e2.gamepad.index];
console.log("Gamepad connected at index: " + gp.index + ": " + gp.id + ". It has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes.");
ga("send", "event", "game", "settings", "controller connected", gp.id);
addEventListener("gamepadbuttondown", this.onButtonDown);
addEventListener("gamepadbuttonup", this.onButtonUp);
_Gamepad.detectControllerType(gp.id);
this.poll();
this.assistInterval = setInterval(_Gamepad.calculateAssist, 67);
});
addEventListener("gamepaddisconnected", (e2) => {
if (e2.gamepad.index == this.index) {
cancelAnimationFrame(this.pollLoop);
clearInterval(this.assistInterval);
this.index = null;
removeEventListener("gamepadbuttondown", this.onButtonDown);
removeEventListener("gamepadbuttonup", this.onButtonUp);
console.log("Gamepad disconnected");
_Gamepad.detectControllerType(getLocText("p_settings_nocontroller"));
}
});
}
static detectControllerType(id) {
if (/xbox|xinput/i.test(id)) {
vueData.controllerType = "xbox";
} else if (/54c/i.test(id)) {
vueData.controllerType = "ps";
} else if (/pro controller/i.test(id)) {
vueData.controllerType = "switchpro";
} else {
vueData.controllerType = "generic";
}
vueData.controllerId = id;
localStore.setItem("controllerId", id);
}
static applyDeadZone(number) {
if (isNaN(number))
return 0;
var threshold = settings.deadzone;
var percentage = (Math.abs(number) - threshold) / (1 - threshold);
if (percentage < 0)
percentage = 0;
return percentage * (number > 0 ? 1 : -1);
}
static poll() {
var gamepads = _Gamepad.getGamepads();
var gp = gamepads[_Gamepad.index];
if (gp) {
if (me && me.playing && document.pointerLockElement || spectate) {
var assistMult = _Gamepad.calculateAssist();
var mult = settings.controllerSpeed * 25e-4 + 5e-3;
if (me.scope) {
mult *= 0.2;
assistMult *= 2;
}
var lookX = _Gamepad.applyDeadZone(gp.axes[2]);
var lookY = _Gamepad.applyDeadZone(gp.axes[3]);
var stickSpeed = Math.length2(lookX, lookY);
mult *= assistMult;
me.yaw_ = Math.radAdd(me.yaw_, lookX * mult);
me.pitch_ = Math.max(
Math.min(
me.pitch_ + lookY * settings.controllerInvert * mult,
1.5
),
-1.5
);
var moveX = _Gamepad.applyDeadZone(gp.axes[0]);
var moveZ = _Gamepad.applyDeadZone(gp.axes[1]);
if (moveX < 0 && _Gamepad.lastMoveX >= 0) {
handleInputDown("left");
} else if (moveX >= 0 && _Gamepad.lastMoveX < 0) {
handleInputUp("left");
}
if (moveX > 0 && _Gamepad.lastMoveX <= 0) {
handleInputDown("right");
} else if (moveX <= 0 && _Gamepad.lastMoveX > 0) {
handleInputUp("right");
}
if (moveZ < 0 && _Gamepad.lastMoveZ >= 0) {
handleInputDown("up");
} else if (moveZ >= 0 && _Gamepad.lastMoveZ < 0) {
handleInputUp("up");
}
if (moveZ > 0 && _Gamepad.lastMoveZ <= 0) {
handleInputDown("down");
} else if (moveZ <= 0 && _Gamepad.lastMoveZ > 0) {
handleInputUp("down");
}
_Gamepad.lastMoveX = moveX;
_Gamepad.lastMoveZ = moveZ;
}
for (var b2 in gp.buttons) {
if (gp.buttons[b2].value > _Gamepad.buttonThreshold && !_Gamepad.buttonState[b2]) {
_Gamepad.buttonState[b2] = true;
dispatchEvent(new CustomEvent("gamepadbuttondown", { detail: b2 }));
} else if (gp.buttons[b2].value <= _Gamepad.buttonThreshold && _Gamepad.buttonState[b2]) {
_Gamepad.buttonState[b2] = false;
dispatchEvent(new CustomEvent("gamepadbuttonup", { detail: b2 }));
}
}
}
_Gamepad.pollLoop = requestAnimationFrame(_Gamepad.poll);
}
static calculateAssist() {
if (!me || !me.playing)
return 1;
var playerPosition = _Gamepad.v1;
var playerDirection = _Gamepad.v2;
var cameraPosition = camera.forwardRay.origin;
var cameraDirection2 = camera.forwardRay.direction;
var bestPlayer = null;
var bestProx = null;
var minRange = 1e7;
for (var player of players) {
if (player && player.id != meId && player.playing && player.actor && player.actor.mesh_.isVisible && (player.team == 0 || player.team != me.team)) {
var range = BABYLON.Vector3.Distance(player.actor.mesh_.position, cameraPosition);
playerPosition.copyFrom(player.actor.mesh_.position);
playerPosition.y += 0.3;
playerPosition.subtractToRef(cameraPosition, playerDirection);
playerDirection.normalize();
cameraDirection2.normalize();
var dp = BABYLON.Vector3.Dot(playerDirection, cameraDirection2);
var prox = (1 - dp) * range * 0.5;
if (range < camera.forwardRay.range + 1 && prox <= 0.05 && range < minRange) {
bestPlayer = player;
minRange = range;
bestProx = prox;
}
}
}
if (bestPlayer) {
return Math.max(bestProx * (1 / 0.05), 0.2);
}
return 1;
}
static onButtonDown(e2) {
if (me)
inputDown("gamepad", e2.detail);
}
static onButtonUp(e2) {
if (me)
inputUp("gamepad", e2.detail);
}
};
Gamepad.v1 = new BABYLON.Vector3();
Gamepad.v2 = new BABYLON.Vector3();
var checkGDPRFuckFuckFUCKCount = 0;
function checkGDPRFuckFuckFUCK() {
if (!isFromEU) {
return;
}
if (checkGDPRFuckFuckFUCKCount > 8) {
return;
}
if (typeof googletag !== "undefined") {
consent = localStore.getItem("consent");
if (consent) {
consent = JSON.parse(consent);
googletag.consented = consent && consent.ofAge && consent.targetedAds || !isFromEU;
vueApp.setPrivacySettings(consent.ofAge, consent.targetedAds);
} else {
consent = {
ofAge: false,
targetedAds: false
};
vueApp.showGdprNotification();
}
console.log("AIP consent: " + googletag.consented);
} else {
setTimeout(() => {
checkGDPRFuckFuckFUCKCount++;
checkGDPRFuckFuckFUCK();
}, 1e3);
}
}
function doConsent() {
ga("send", "event", "privacy", "age gate", "agree");
consent = {
ofAge: true,
targetedAds: true
};
googletag.consented = true;
vueApp.setPrivacySettings(true, true);
localStore.setItem("consent", JSON.stringify(consent));
}
function doNotConsent() {
ga("send", "event", "privacy", "age gate", "disagree");
googletag.consented = false;
vueApp.setPrivacySettings(false, false);
localStore.setItem("consent", JSON.stringify(consent));
}
function setOfAge(val) {
consent.ofAge = val;
ga("send", "event", "privacy", "of age", val ? "yes" : "no");
if (!val) {
consent.targetedAds = false;
googletag.consented = false;
}
localStore.setItem("consent", JSON.stringify(consent));
}
function setTargetedAds(allow) {
consent.targetedAds = allow;
googletag.consented = allow;
ga("send", "event", "privacy", "targetedAds", allow ? "yes" : "no");
localStore.setItem("consent", JSON.stringify(consent));
}
(function(i2, s, o, g, r, a, m) {
i2["GoogleAnalyticsObject"] = r;
i2[r] = i2[r] || function() {
(i2[r].q = i2[r].q || []).push(arguments);
}, i2[r].l = 1 * /* @__PURE__ */ new Date();
a = s.createElement(o), m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m);
a.onload = function() {
if (window.ga && ga.create) {
oldga = window.ga;
window.ga = newga;
}
};
})(window, document, "script", "https://www.google-analytics.com/analytics.js", "ga");
var oldga = window.ga;
var newga = function() {
oldga.apply(window, arguments);
var method = arguments[0];
switch (method) {
case "create":
break;
case "set": {
var name = arguments[1];
var value = arguments[2];
var props = {};
props[name] = value;
gtag("set", "user_properties", props);
break;
}
case "send": {
var params = {
hitType: arguments[1]
};
switch (params.hitType) {
case "pageview":
gtag("pageview", {
page_location: location.href
});
break;
case "event":
if (typeof arguments[2] === "object") {
params = Object.assign(params, arguments[2]);
} else {
params.eventCategory = arguments[2];
params.eventAction = arguments[3];
params.eventLabel = arguments[4];
params.eventValue = arguments[5];
if (typeof arguments[6] === "object") {
params = Object.assign(params, arguments[6]);
}
}
gtag("event", params.eventAction, params);
break;
case "timing":
params.timingCategory = arguments[2];
params.timingVar = arguments[3];
params.timingValue = arguments[4];
params.timingLabel = arguments[5];
gtag("event", "timing_complete", params);
break;
}
break;
}
}
};
window.ga = newga;
ga("set", "anonymizeIp", !isFromEU);
ga("create", "UA-105800112-1", {
cookieDomain: "auto",
siteSpeedSampleRate: 10,
cookieFlags: "samesite=none;secure"
});
ga("send", "pageview");
ga("set", "account", "web");
var gaSendEvents = (eventArray, hitType) => {
hitType = hitType || "event";
eventArray.forEach((el) => {
ga("send", hitType, {
eventCategory: el[0],
eventAction: el[1],
eventLabel: el[2],
eventValue: el[3]
});
});
};
var gaSessionPlayTime = (startTime, map2) => {
map2 = map2 || "";
let timePlayed = Date.now() - startTime;
ga("send", "timing", "game", "play time", timePlayed);
fbq("trackCustom", "EndGame", { timePlayed });
if (map2) {
ga("send", "timing", "Maps", map2, timePlayed);
}
};
var flashColors = [
new BABYLON.Color3(1, 1, 0),
new BABYLON.Color3(0, 0.5, 1),
new BABYLON.Color3(1, 0, 0)
];
function GrenadeActor(grenade) {
this.grenade = grenade;
this.scene = grenade.scene;
this.meshes = {};
for (let i2 = 0; i2 < G.catalog.grenades.length; i2++) {
let grenade2 = G.catalog.grenades[i2];
let mesh2 = cloneMesh(grenade2.item_data.meshName, this.scene);
mesh2.material = this.scene.getMaterialByName("emissive");
this.meshes[grenade2.id] = mesh2;
mesh2.setEnabled(false);
}
this.mesh_ = null;
this.beep = false;
this.flashColor = null;
}
GrenadeActor.prototype.dispose = function() {
for (let mesh2 of Object.values(this.meshes)) {
mesh2.dispose();
}
};
GrenadeActor.prototype.throw = function() {
this.mesh_ = this.meshes[this.grenade.player_.grenadeItem.id];
this.mesh_.setEnabled(true);
this.mesh_.position.x = this.grenade.x;
this.mesh_.position.y = this.grenade.y;
this.mesh_.position.z = this.grenade.z;
if (this.grenade.player_.id == meId) {
this.flashColor = flashColors[0];
} else {
this.flashColor = flashColors[this.grenade.player_.team];
}
pAudio.play("grenade_pin", this.mesh_.position);
this.bounce();
};
GrenadeActor.prototype.update = function(delta) {
if (!this.grenade.resting) {
this.mesh_.position.x += (this.grenade.x - this.mesh_.position.x) * 0.5;
this.mesh_.position.y += (this.grenade.y - this.mesh_.position.y) * 0.5;
this.mesh_.position.z += (this.grenade.z - this.mesh_.position.z) * 0.5;
this.mesh_.rotation.x += this.rx;
this.mesh_.rotation.y += this.ry;
this.mesh_.rotation.z += this.rz;
}
if (Math.sqrt(this.grenade.ttl * 2) % 2 > 1) {
if (this.beep == false) {
pAudio.play("grenade_beep", this.mesh_.position);
this.beep = true;
}
this.mesh_.emissiveColor = this.flashColor;
} else {
this.mesh_.emissiveColor = BABYLON.Color3.Black();
this.beep = false;
}
};
GrenadeActor.prototype.remove = function() {
this.mesh_.setEnabled(false);
};
GrenadeActor.prototype.bounce = function() {
var s = Math.length3(this.grenade.dx, this.grenade.dy, this.grenade.dz);
this.rx = (Math.random() * 2 - 1) * s;
this.ry = (Math.random() * 2 - 1) * s;
this.rz = (Math.random() * 2 - 1) * s;
};
GrenadeActor.prototype.stop = function() {
this.rx = 0;
this.ry = 0;
this.rz = 0;
};
var GunActor = class {
constructor(gun, meshName) {
this.gun_ = gun;
this.meshName = meshName;
this.scene = gun.scene;
this.standardMeshName = gun.constructor.standardMeshName;
this.playerActor = gun.player_.actor;
this.skeleton = cloneSkeleton("gun_" + this.standardMeshName + "_skeleton", this.scene);
this.roundsFired = 0;
this.dryFireSound = "gun_eggk47_dry_fire";
}
setup(muzFlashZ) {
this.gunMesh_ = cloneMesh(this.meshName, this.scene, this.playerActor.gunContainer);
this.gunMesh_.material = getMaterialByName("standard", this.scene);
this.gunMesh_.skeleton = this.skeleton;
this.gunMesh_.setEnabled(false);
if (muzFlashZ) {
this.muzzleFlash = cloneMesh("muzzleFlash", this.scene, this.playerActor.gunContainer);
this.muzzleFlash.material = getMaterialByName("muzzleFlash", this.scene);
this.muzzleFlash.setEnabled(false);
this.muzzleFlash.position.x = 0.25;
this.muzzleFlash.position.z = muzFlashZ;
this.muzzleFlash.scaling.copyFromFloats(0.7, 0.7, 0.7);
}
if (this.gun_.player_.id == meId) {
this.gunMesh_.setRenderingGroupId(2);
if (this.muzzleFlash)
this.muzzleFlash.setRenderingGroupId(2);
}
}
addSoundEvent(animation, frame, sound) {
var range = this.skeleton.getAnimationRange(animation);
frame += range.from;
function getPlayFunction(sound2, position) {
return function() {
pAudio.play(sound2, position, true);
};
}
var event = new BABYLON.AnimationEvent(frame, getPlayFunction(sound, this.gun_.player_.actor.mesh_.position));
this.skeleton.bones[0].animations[0].addEvent(event);
}
dispose() {
this.gunMesh_.dispose();
}
inspect() {
this.skeleton.beginAnimation("inspect");
}
restPose() {
let skeleton = this.skeleton;
var range = skeleton.getAnimationRange("fire");
if (gameScene !== void 0)
gameScene.beginAnimation(skeleton, range.from, range.from);
}
stow() {
pAudio.play("weapon_swap", this.gun_.player_.actor.mesh_.position, true);
this.scene.beginAnimation(this.playerActor.gunContainer, 0, 25, false, 1, () => {
this.gunMesh_.setEnabled(false);
this.gun_.equip();
});
}
equip(speed) {
this.gun_.player_.meleeWeapon.actor.weaponMesh.setEnabled(false);
this.playerActor.setWeaponSkeleton(this.skeleton);
this.playerActor.gunContainer.setEnabled(false);
this.scene.beginAnimation(this.playerActor.gunContainer, 30, 55, false, speed || 1);
this.gunMesh_.setEnabled(true);
this.roundsFired = 0;
setTimeout(() => {
this.playerActor.gunContainer.setEnabled(true);
}, 1);
}
dryFire() {
pAudio.play(this.dryFireSound, this.gun_.player_.actor.mesh_.position, true);
}
denyFire() {
reticle.fireDenied();
pAudio.play(this.dryFireSound, this.gun_.player_.actor.mesh_.position, true);
pAudio.play(this.denyFireSound, this.gun_.player_.actor.mesh_.position, true);
}
fire() {
if (!this.gun_.constructor.burst || this.roundsFired % this.gun_.constructor.burst == 0) {
if (this.fireSound)
pAudio.play(this.fireSound, this.gun_.player_.actor.mesh_.position, true);
this.skeleton.beginAnimation("fire");
}
this.roundsFired++;
if (this.muzzleFlash) {
this.muzzleFlash.rotation.z = Math.random() * 3.141;
this.muzzleFlash.setEnabled(true);
var that = this;
setTimeout(function() {
that.muzzleFlash.setEnabled(false);
}, 33);
}
}
reload() {
if (this.gun_.longReloadTime == this.gun_.shortReloadTime) {
this.skeleton.beginAnimation("reload", false, this.gun_.constructor.reloadTimeMod);
} else if (this.gun_.ammo.rounds > 0) {
this.skeleton.beginAnimation("shortReload", false, this.gun_.constructor.reloadTimeMod);
} else {
this.skeleton.beginAnimation("longReload", false, this.gun_.constructor.reloadTimeMod);
}
}
getFireSound(gun, meshName, defaultSound) {
if (PremMeshNames[gun].includes(meshName)) {
const meshFireSound = meshName + "_fire";
return BAWK.sounds[meshFireSound] ? meshFireSound : defaultSound;
}
return defaultSound;
}
update() {
}
};
var Eggk47Actor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 0.9;
this.scopeY = 0.0438;
this.setup(0.6);
this.fireSound = this.getFireSound("Soldier", meshName, "gun_eggk47_fire");
this.addSoundEvent("shortReload", 30, "gun_eggk47_remove_mag");
this.addSoundEvent("shortReload", 123, "gun_eggk47_insert_mag");
this.addSoundEvent("longReload", 30, "gun_eggk47_remove_mag");
this.addSoundEvent("longReload", 123, "gun_eggk47_insert_mag");
this.addSoundEvent("longReload", 155, "gun_eggk47_full_cycle");
}
};
var DozenGaugeActor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 1;
this.scopeY = 0.072;
this.setup(0.6);
this.fireSound = this.getFireSound("Scrambler", meshName, "gun_dozenGauge_fire");
this.addSoundEvent("reload", 0, "gun_dozenGauge_open");
this.addSoundEvent("reload", 80, "gun_dozenGauge_load");
this.addSoundEvent("reload", 115, "gun_dozenGauge_close");
}
};
var CSG1Actor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 0.5;
this.scopeY = 0.0345;
this.setup(0.6);
this.fireSound = this.getFireSound("Ranger", meshName, "gun_csg1_fire");
this.addSoundEvent("shortReload", 25, "gun_eggk47_remove_mag");
this.addSoundEvent("shortReload", 125, "gun_eggk47_insert_mag");
this.addSoundEvent("longReload", 30, "gun_csg1_pull_action");
this.addSoundEvent("longReload", 75, "gun_eggk47_remove_mag");
this.addSoundEvent("longReload", 160, "gun_eggk47_insert_mag");
this.addSoundEvent("longReload", 190, "gun_csg1_release_action");
}
};
var Cluck9mmActor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 1.1;
this.scopeY = 0.069;
this.setup(0.48);
this.fireSound = this.getFireSound("Secondary", meshName, "gun_cluck9mm_fire");
this.addSoundEvent("shortReload", 15, "gun_cluck9mm_remove_mag");
this.addSoundEvent("shortReload", 110, "gun_cluck9mm_insert_mag");
this.addSoundEvent("longReload", 15, "gun_cluck9mm_remove_mag");
this.addSoundEvent("longReload", 110, "gun_cluck9mm_insert_mag");
this.addSoundEvent("longReload", 155, "gun_eggk47_full_cycle");
}
};
var RPEGGActor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 0.9;
this.scopeY = 0.1 - 0.0862;
this.setup(0.51);
this.fireSound = this.getFireSound("Eggsploder", meshName, "gun_rpegg_fire");
this.denyFireSound = "gun_rpegg_deny_fire";
this.addSoundEvent("reload", 115, "gun_rpegg_load");
}
};
var SMGActor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 1;
this.scopeY = 0.1 - 0.09635;
this.setup(0.55);
this.fireSound = this.getFireSound("Whipper", meshName, "gun_smg_fire");
this.addSoundEvent("shortReload", 30, "gun_eggk47_remove_mag");
this.addSoundEvent("shortReload", 150, "gun_eggk47_insert_mag");
this.addSoundEvent("longReload", 30, "gun_eggk47_remove_mag");
this.addSoundEvent("longReload", 150, "gun_eggk47_insert_mag");
this.addSoundEvent("longReload", 185, "gun_smg_cycle");
}
};
var M24Actor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 0.4;
this.scopeY = 0.1 - 0.03507;
this.setup(0.6);
this.fireSound = this.getFireSound("Crackshot", meshName, "gun_m24_fire");
this.addSoundEvent("reload", 10, "gun_m24_bolt_open");
this.addSoundEvent("reload", 75, "gun_eggk47_insert_mag");
this.addSoundEvent("reload", 94, "gun_m24_bolt_close");
}
};
var AUGActor = class extends GunActor {
constructor(gun, meshName) {
super(gun, meshName);
this.scopeFov = 0.7;
this.scopeY = 0.0385;
this.setup(0.6);
this.fireSound = this.getFireSound("TriHard", meshName, "gun_aug_fire");
this.addSoundEvent("shortReload", 28, "gun_aug_remove_mag");
this.addSoundEvent("shortReload", 118, "gun_aug_insert_mag");
this.addSoundEvent("longReload", 28, "gun_aug_remove_mag");
this.addSoundEvent("longReload", 118, "gun_aug_insert_mag");
this.addSoundEvent("longReload", 153, "gun_aug_cycle");
}
};
function fetchHouseAds() {
getRequest("data/housePromo.json?" + Date.now(), function(err, res) {
if (Object.keys(HouseAds).length === 0 && HouseAds.constructor === Object) {
houseAds = { big: [], small: [], bigBanner: [], houseAdPercentChance: 100, smHouseAds: [], shellLogo: [] };
} else {
const tags = { socialMedia: "", premFeat: "" };
houseAds = HouseAds;
preLoadHouseAdSmall();
console.log("special items tag: " + houseAds.specialItemsTag);
if (hasValue(houseAds.specialItemsTag) && G.catalog.getTaggedItems(houseAds.specialItemsTag).length > 0) {
vueApp.useSpecialItemsTag(houseAds.specialItemsTag);
} else {
vueApp.disableSpecialItems();
}
if (hasValue(houseAds.featuredSocialMedia)) {
tags.socialMedia = houseAds.featuredSocialMedia;
}
if (hasValue(houseAds.premFeatured)) {
tags.premFeat = houseAds.premFeatured;
premFeatTag[tags.premFeat] = true;
}
if (houseAds.smHouseAds.length > 0) {
vueApp.ui.houseAds.homeScreen.push(...houseAds.smHouseAds);
}
vueApp.useTags(tags);
}
houseAdsLoaded = true;
});
}
function requestJson(filename, callback) {
getRequest(filename + "?" + Date.now(), (err, res) => {
let dataItems = [];
if (err === 404) {
console.log("Accept it and move on.");
} else {
try {
const data2 = JSON.parse(res);
if (data2.length > 0) {
data2.forEach((item) => dataItems.push(item));
}
} catch (e2) {
console.log("News request error: ", e2);
}
}
callback(dataItems);
});
}
function preLoadHouseAdSmall() {
var adIdxs = [];
for (var i2 = 0; i2 < houseAds.small.length; i2++) {
if (houseAds.small[i2].active) {
adIdxs.push(i2);
if (houseAds.small[i2].weighted) {
adIdxs.push(i2);
}
}
}
if (adIdxs.length > 0) {
vueApp.useHouseAdSmall(houseAds.small[adIdxs[Math.floor(Math.random() * adIdxs.length)]]);
}
}
function clickedHouseAdSmall(smallHouseAd) {
ga("send", "event", {
eventCategory: "House banner ad",
eventAction: "click",
eventLabel: smallHouseAd.label
});
clickedHouseLink(smallHouseAd);
}
function clickedHouseAdBig(bigAd) {
ga("send", "event", {
eventCategory: "Big ad",
eventAction: "click",
eventLabel: bigAd.label
});
clickedHouseLink(bigAd);
}
function hasHouseLink(obj) {
return obj.link || obj.linksToTaggedItems || obj.linksToItemId || obj.linksToNugget || obj.linksToPhotoBooth;
}
function linksToItemId(linkObj) {
if (isString(linkObj.linksToItemId)) {
linkObj.linksToItemId = parseInt(linkObj.linksToItemId, 10);
}
var item = catalog.findItemById(linkObj.linksToItemId);
vueApp.showItemOnEquipScreen(item);
}
function clickedHouseLink(linkObj) {
switch (linkObj.linksTo) {
case "linksToTaggedItems":
break;
case "linksToItemId":
linksToItemId(linkObj);
break;
case "linksToNugget":
showNugget = true;
tryShowNugget();
break;
case "linksToPhotoBooth":
openPhotoBooth();
break;
case "linksToVipStore":
vueApp.showSubStorePopup();
break;
case "linkToShop":
vueApp.openEquipSwitchTo(parseInt(linkObj.linkToShop, 10));
break;
case "linkToChw":
vueApp.showNuggyPopup();
break;
case "linkToBlackFriday":
vueApp.showEggStorePopup();
break;
case "linkToEggOrg":
vueApp.showSelectedTaggedItemsOnEquipScreen("EGGORG");
break;
case "linkToTwitch":
window.open(dynamicContentPrefix + "twitch?utm_medium=referral&utm_campaign=featureslot", "_blank");
break;
case "linksToCreateGame":
vueApp.showCreateGamePopup();
break;
default:
if (linkObj.link.length > 1 && crazyGamesActive) {
window.open(linkObj.link[1], "_window");
} else {
window.open(linkObj.link[0], "_window");
}
break;
}
ga("send", "event", "home-display-ad", "click", linkObj.label.toLowerCase().replace(/ /g, "-"));
}
function clickedWebFeedItem(item) {
function gaEvent(clicked) {
ga("send", "event", "newsItem", "clicked", clicked);
}
if ("linksToItemId" in item) {
let itemId = G.catalog.findItemById(parseInt(item.linksToItemId, 10));
vueApp.showItemOnEquipScreen(itemId);
gaEvent(`item=${itemId.name}`);
return;
}
if ("linksToTaggedItems" in item) {
if (item.linksToTaggedItems == 1) {
showTaggedItems = houseAds.specialItemsTag;
} else {
showTaggedItems = item.linksToTaggedItems;
}
openShopOnly = true;
tryShowTaggedItems();
gaEvent(`tagged=${item.linksToTaggedItems}`);
return;
}
if ("linksToChangeLog" in item) {
vueApp.showChangelogPopup();
gaEvent("sschangelog");
return;
}
if ("link" in item) {
window.open(item.link, "_window");
gaEvent(item.link);
return;
}
if ("linksToPhotoBooth" in item) {
openPhotoBooth();
gaEvent("openPhotoBooth");
return;
}
if ("linksToNugget" in item) {
showNugget = true;
tryShowNugget();
gaEvent("nugget");
}
if ("linksToEggStoreItem" in item) {
vueApp.showPopupEggStoreSingle(item.linksToEggStoreItem);
gaEvent(`skuItem=${item.linksToEggStoreItem}`);
return;
}
if ("linksToVipStore" in item) {
vueApp.showSubStorePopup();
gaEvent(`skuItem=${item.linksToVipStore}`);
}
if ("linksToKotc" in item) {
vueApp.showKotcInstrucPopup();
}
}
var getHouseAd = (size) => {
if (!houseAds.length) {
return;
}
const ACTIVE = houseAds[size].filter((i2) => i2.active);
if (!ACTIVE.length) {
return;
}
const PRIORITYLIST = [];
const VIPCOUNT = ACTIVE.filter((i2) => i2.label.includes("VIP")).length;
let VIPWEIGHT = Math.round(50 / 100 * ACTIVE.length / VIPCOUNT);
if (!isFinite(VIPWEIGHT))
VIPWEIGHT = 1;
const VIPPRIORITY = ACTIVE.map((x) => {
const LABEL = x.label.toUpperCase();
x.priority = 1;
if (LABEL.includes("VIP")) {
x.priority = VIPWEIGHT;
}
return x;
});
for (let i2 = 0; i2 < VIPPRIORITY.length; ++i2) {
for (let j = 0; j < VIPPRIORITY[i2].priority; ++j) {
PRIORITYLIST.push(VIPPRIORITY[i2]);
}
}
return PRIORITYLIST[Math.floor(Math.random() * PRIORITYLIST.length)];
};
function ItemActor(kind) {
this.kind = kind;
this.scene = gameScene;
}
ItemActor.prototype.update = function(delta) {
this.mesh_.rotation.y += 0.03 * delta;
};
ItemActor.prototype.remove = function() {
this.mesh_.setEnabled(false);
};
function AmmoActor() {
ItemActor.call(this, ItemManager.AMMO);
this.mesh_ = this.scene.getMeshByName("ammo").createInstance("");
this.mesh_.setEnabled(false);
if (shadowGen)
shadowGen.getShadowMap().renderList.push(this.mesh_);
}
AmmoActor.prototype = Object.create(ItemActor.prototype);
AmmoActor.prototype.constructor = ItemActor;
function GrenadeItemActor() {
ItemActor.call(this, ItemManager.GRENADE);
this.mesh_ = this.scene.getMeshByName("grenadeItem").createInstance("");
this.mesh_.setEnabled(false);
if (shadowGen)
shadowGen.getShadowMap().renderList.push(this.mesh_);
}
GrenadeItemActor.prototype = Object.create(ItemActor.prototype);
GrenadeItemActor.prototype.constructor = ItemActor;
function ItemManager() {
this.pools = [
new Pool(function() {
return new ItemManager.Constructors[ItemManager.AMMO]();
}, 100),
new Pool(function() {
return new ItemManager.Constructors[ItemManager.GRENADE]();
}, 20)
];
}
ItemManager.AMMO = 0;
ItemManager.GRENADE = 1;
ItemManager.Constructors = [
AmmoActor,
GrenadeItemActor
];
ItemManager.prototype.update = function(delta) {
for (var k = 0; k < this.pools.length; k++) {
this.pools[k].forEachActive(function(item) {
item.update(delta);
item.mesh_.isVisible = isMeshVisible(item.mesh_);
});
}
};
ItemManager.prototype.spawnItem = function(id, kind, x, y, z) {
var item = this.pools[kind].retrieve(id);
item.mesh_.setEnabled(true);
item.mesh_.position.x = x;
item.mesh_.position.y = y;
item.mesh_.position.z = z;
if (testing)
item.mesh_.freezeWorldMatrix();
};
ItemManager.prototype.collectItem = function(kind, id) {
var p = this.pools[kind];
p.recycle(p.objects[id]);
p.objects[id].remove();
};
ItemManager.prototype.recycleAllItems = function() {
var that = this;
for (var k = 0; k < this.pools.length; k++) {
this.pools[k].forEachActive(function(item) {
that.pools[k].recycle(item);
item.remove();
});
}
};
function ItemRenderer() {
this.scene = new BABYLON.Scene(G.engine);
this.scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
this.canvas = G.engine.getRenderingCanvas();
this.scene.sunLight = {
direction: new BABYLON.Vector3(0.2, 1, 0.1),
diffuse: new BABYLON.Color3.White()
};
this.meshRenderStaging = {};
loadMaterials(this.scene);
this.camera = new BABYLON.ArcRotateCamera("", 0, 0, 0, new BABYLON.Vector3(0, 0, 0), this.scene);
this.scene.activeCameras.push(this.camera);
this.camera.fov = 0.5;
this.camera.maxZ = 100;
this.camera.minZ = 0.01;
this.stampSprites = new BABYLON.SpriteManager("", "img/stamps.png?v=" + version, 1024, 128, this.scene);
this.stampSprite = new BABYLON.Sprite("", this.stampSprites);
this.stampSprite.size = 1;
}
ItemRenderer.prototype.renderToCanvas = function(item, destCanvas, callback) {
let meshName = item.item_data.meshName;
this.camera.alpha = 0;
this.camera.beta = Math.PI90;
var mesh2 = cloneMesh(meshName, this.scene);
mesh2.layerMask = 1;
this.camera.layerMask = 1;
mesh2.computeWorldMatrix();
this.camera.computeWorldMatrix();
let stage = this.meshRenderStaging[meshName];
mesh2.position.copyFrom(stage.position);
mesh2.rotation.copyFrom(stage.rotation);
this.camera.radius = stage.radius;
this.scene.render();
mesh2.dispose();
var ctx = destCanvas.getContext("2d");
ctx.clearRect(0, 0, 256, 256);
ctx.drawImage(this.canvas, (this.canvas.width - this.canvas.height) / 2, 0, this.canvas.height, this.canvas.height, 0, 0, 256, 256);
this.camera.layerMask = 0;
this.scene.render();
if (callback) {
callback();
}
};
ItemRenderer.prototype.renderStampToCanvas = function(stampItem, destCanvas, callback) {
var x = stampItem.item_data.x;
var y = stampItem.item_data.y;
this.stampSprites.layerMask = 2;
this.camera.layerMask = 2;
this.stampSprite.cellIndex = x + y * 32;
this.camera.alpha = 0;
this.camera.beta = 0;
this.camera.radius = 2.5;
this.scene.render();
var ctx = destCanvas.getContext("2d");
ctx.clearRect(0, 0, 256, 256);
ctx.drawImage(this.canvas, (this.canvas.width - this.canvas.height) / 2, 0, this.canvas.height, this.canvas.height, 0, 0, 256, 256);
this.camera.layerMask = 0;
this.scene.render();
if (callback) {
callback();
}
};
ItemRenderer.prototype.calculateItemAlignments = function() {
let items = [...G.catalog.hats, ...G.catalog.grenades, ...G.catalog.melee];
for (let i3 = 0; i3 < CharClass.length; i3++) {
items.push(...G.catalog.forClass[i3].forWeaponSlot[Slot.Primary]);
items.push(...G.catalog.forClass[i3].forWeaponSlot[Slot.Secondary]);
}
this.camera.alpha = 0;
this.camera.beta = Math.PI90;
this.camera.radius = 1;
G.engine.setSize(256, 256);
for (let item of items) {
let meshName = item.item_data.meshName;
let mesh2 = cloneMesh(meshName, this.scene);
var verts = mesh2.getVerticesData(BABYLON.VertexBuffer.PositionKind);
if (!verts) {
alert(`${mesh2.name} is referenced in items.js, but is missing mesh data`);
continue;
}
let stage;
switch (item.item_type_id) {
case ItemType2.Hat:
stage = {
radius: 1.3,
rotation: new BABYLON.Vector3(0.25, 2, 0),
position: new BABYLON.Vector3(0, -0.25, 0)
};
break;
case ItemType2.Grenade:
stage = {
radius: 0.4,
rotation: new BABYLON.Vector3(0, -1.3, 0),
position: new BABYLON.Vector3(0, -0.01, 0)
};
break;
case ItemType2.Melee:
stage = {
radius: 0.4,
rotation: new BABYLON.Vector3(-0.5, 4, -1.2),
position: new BABYLON.Vector3(0, 0.02, 0.12)
};
break;
case ItemType2.Primary:
stage = {
radius: 1.3,
rotation: new BABYLON.Vector3(-0.7, 0, 0),
position: new BABYLON.Vector3(0, -0.1, -0.1)
};
break;
case ItemType2.Secondary:
stage = {
radius: 1,
rotation: new BABYLON.Vector3(0, 0, 0),
position: new BABYLON.Vector3(0, 0.05, -0.32)
};
break;
default:
}
mesh2.position.copyFrom(stage.position);
mesh2.rotation.copyFrom(stage.rotation);
mesh2.computeWorldMatrix();
this.camera.radius = stage.radius;
if (item.item_type_id !== ItemType2.Grenade) {
this.scene.updateTransformMatrix();
var min = { x: 1e4, y: 1e4 };
var max = { x: -1e4, y: -1e4 };
for (var i2 = 0; i2 < verts.length; i2 += 3) {
var sp = BABYLON.Vector3.Project(
new BABYLON.Vector3(verts[i2], verts[i2 + 1], verts[i2 + 2]),
mesh2.getWorldMatrix(),
this.scene.getTransformMatrix(),
this.camera.viewport.toGlobal(G.engine)
);
min.x = Math.min(min.x, sp.x);
max.x = Math.max(max.x, sp.x);
min.y = Math.min(min.y, sp.y);
max.y = Math.max(max.y, sp.y);
}
var cx = (max.x + min.x) / 2 - 128;
var cy = (max.y + min.y) / 2 - 128;
stage.position.z -= cx / 512;
stage.position.y += cy / 512;
}
mesh2.dispose();
this.meshRenderStaging[meshName] = stage;
}
resize();
};
var Matchmaker = class {
static connect() {
return new Promise((res, fail) => {
var root = dynamicContentRoot ? dynamicContentRoot : location.host;
var url = `${isHttps() ? "wss" : "ws"}://` + root + "/matchmaker/";
this.ws = new ReliableWebSocket(url);
this.ws.onopen = () => {
res(this.ws);
};
this.ws.onmessage = (e2) => this.handleMatchmakerMessage(e2);
this.ws.onerror = () => {
};
});
}
static getRegions() {
return new Promise((res, fail) => {
this.ws.send('{ "command": "regionList" }');
this.ws.onmessage = (e2) => {
let data2 = JSON.parse(e2.data);
switch (data2.command) {
case "regionList":
this.ws.onerror = (e3) => {
};
this.regionList = data2.regionList;
for (let r of this.regionList) {
r.locKey = "server_" + r.id;
r.ping = null;
}
vueApp.regionList = this.regionList;
res();
break;
default:
this.handleMatchmakerMessage(e2);
break;
}
};
this.ws.onerror = (e2) => {
fail(e2);
this.handleError(e2);
};
});
}
static joinPrivateGame(params) {
return new Promise((res, fail) => {
let opts = {
command: "joinGame",
id: params.joinCode.toUpperCase(),
observe: params.observe,
sessionId: G.playerAccount.sessionId
};
this.ws.send(JSON.stringify(opts));
this.ws.onmessage = (e2) => {
let data2 = JSON.parse(e2.data);
if (data2.error) {
fail(CloseCode[data2.error]);
} else {
switch (data2.command) {
case "gameFound":
this.ws.onerror = (e3) => {
};
res(data2);
break;
default:
this.handleMatchmakerMessage(e2);
break;
}
}
};
this.ws.onerror = (e2) => {
fail(e2);
this.handleError(e2);
};
});
}
static findGame(params) {
return new Promise((res, fail) => {
let region = vueApp.currentRegionId;
let opts = {
command: "findGame",
region,
playType: params.playType,
gameType: params.gameType,
sessionId: G.playerAccount.sessionId
};
if (params.playType === vueData.playTypes.createPrivate) {
opts.map = params.mapIdx;
}
this.ws.send(JSON.stringify(opts));
this.ws.onmessage = (e2) => {
let data2 = JSON.parse(e2.data);
if (data2.error) {
fail(CloseCode[data2.error]);
} else {
switch (data2.command) {
case "gameFound":
this.ws.onerror = (e3) => {
};
res(data2);
break;
default:
this.handleMatchmakerMessage(e2);
break;
}
}
};
this.ws.onerror = (e2) => {
fail(e2);
this.handleError(e2);
};
});
}
static handleMatchmakerMessage(e2) {
let data2 = JSON.parse(e2.data);
switch (data2.command) {
case "notice":
this.handleNotices(data2.notices);
break;
}
}
static handleNotices(notices) {
Object.keys(notices).forEach((k) => {
switch (k) {
case "announcement":
vueData.announcementMessage = notices[k];
break;
case "version":
if (notices[k] !== version) {
if (!localStorage.getItem("cacheNuked")) {
localStorage.setItem("cacheNuked", true);
nukeCacheAndReload();
} else {
console.log("Wrong client version");
let interval2 = setInterval(() => {
if (vueApp) {
clearInterval(interval2);
vueApp.showGenericPopup("wrong_version", "wrong_version_msg", "ok");
}
}, 100);
}
} else {
localStorage.removeItem("cacheNuked");
}
break;
}
});
}
static handleError(e2) {
this.ws.onerror = (e3) => {
};
Loader2.hide();
vueApp.hideSpinner();
console.log("Failed to connect to Matchmaker", e2);
vueApp.showGenericPopup("matchmaker_offline", "matchmaker_offline_msg", "ok");
}
};
var MeleeWeaponActor = class {
constructor(weapon, meshName) {
this.weapon = weapon;
this.meshName = meshName;
this.scene = weapon.scene;
this.player_ = weapon.player_;
this.playerActor = weapon.player_.actor;
this.skeleton = cloneSkeleton("melee_skeleton", this.scene);
this.weaponMesh = cloneMesh(this.meshName, this.scene, this.playerActor.gunContainer);
this.weaponMesh.skeleton = this.skeleton;
this.weaponMesh.material = getMaterialByName("standard", this.scene);
this.weaponMesh.setEnabled(false);
this.swingSounds = this.getSwingSounds(meshName);
if (this.weapon.player_.id == meId) {
this.weaponMesh.setRenderingGroupId(2);
}
}
getSwingSounds(meshName) {
if (PremMeshNames.Melee.includes(meshName)) {
return Object.keys(BAWK.sounds).filter((s) => s.startsWith(meshName));
}
return ["melee_whisk_a", "melee_whisk_b"];
}
dispose() {
this.weaponMesh.dispose();
}
stow() {
this.weaponMesh.setEnabled(false);
}
attack() {
this.skeleton.beginAnimation("melee");
setTimeout(() => {
let i2 = Math.randomInt(0, this.swingSounds.length);
pAudio.play(this.swingSounds[i2], this.playerActor.mesh_.position, true);
}, 68);
}
};
function PaperDoll() {
this.posingItems = {
[ItemType2.Primary]: null,
[ItemType2.Secondary]: null,
[ItemType2.Grenade]: null,
[ItemType2.Melee]: null,
[ItemType2.Hat]: null,
[ItemType2.Stamp]: null
};
this.grenadeOnHip = false;
this.camX = 0;
this.camY = 0.35;
this.camRadius = 3.4;
this.rotY = 0;
this.rotX = 0;
this.jump = 0;
this.turnCountdown = 60;
this.buyingItem = null;
this.autoUpdate = true;
this.scaleSizes = [1, 1.25, 1.5];
this.dmg = 100;
this.setupScene();
this.onResourcesLoaded();
}
PaperDoll.prototype.onResourcesLoaded = function() {
var outer = this;
this.startRendering();
try {
let PlayerAvatar = function(c) {
this.scene = outer.scene;
this.id = -1;
this.name = "";
this.x_ = 0;
this.y_ = 0;
this.z_ = 0;
this.hp_ = 100;
this.hatItem = G.playerAccount.hatItem;
this.stampItem = G.playerAccount.stampItem;
this.shellColor = G.playerAccount.colorIdx;
this.meleeItem = G.playerAccount.meleeItem;
this.actor = new PlayerActor(this);
this.actor.mesh_.rotation.y = outer.rotY;
this.meleeWeapon = new MeleeWeapon(this);
this.weapon = new G.classes[c].weapon(this, meshName);
};
var meshName = G.playerAccount.getPrimaryWeapon().item_data.meshName;
this.dualAvatar = new PlayerAvatar(G.playerAccount.classIdx);
this.dualAvatar.actor.bodyMesh_.setEnabled(false);
this.dualAvatar.actor.hands.material.backFaceCulling = false;
this.dualAvatar.actor.foreBone.setScale(BABYLON.Vector3.Zero());
this.dualAvatar.actor.setupStowAnims(0, true);
this.dualAvatar.weapon.actor.equip();
this.avatar = new PlayerAvatar(G.playerAccount.classIdx);
this.avatar.actor.foreBone.setScale(BABYLON.Vector3.Zero());
this.avatar.actor.setupStowAnims(0);
this.avatar.weapon.actor.equip();
var lastNow = Date.now();
this.scene.registerBeforeRender(function() {
var now2 = Date.now();
var delta = now2 - lastNow;
lastNow = now2;
delta /= 17;
outer.update(delta);
});
} catch (e2) {
console.log(e2);
}
this.manualOrientation = false;
this.isMouseDown = false;
this.drag = false;
this.equipContainer = document.getElementById("equip_purchase_top");
this.dollContainer = document.getElementById("paper_doll_container");
this.equipContainer.addEventListener("mousemove", (e2) => {
this.manualOrientation = true;
if (e2.target.id !== "equip_purchase_top") {
return false;
}
this.drag = false;
this.pointEggEvent(e2);
});
this.dollContainer.addEventListener("mousemove", (e2) => {
this.manualOrientation = true;
this.drag = false;
this.pointEggEvent(e2);
});
this.equipContainer.addEventListener("pointerleave", (e2) => {
this.manualOrientation = false;
this.isMouseDown = false;
});
this.dollContainer.addEventListener("pointerleave", (e2) => {
this.manualOrientation = false;
this.isMouseDown = false;
});
this.equipContainer.addEventListener("mousedown", (e2) => {
if (!this.autoUpdate) {
this.isMouseDown = true;
this.drag = true;
}
});
this.dollContainer.addEventListener("mousedown", (e2) => {
if (!this.autoUpdate) {
this.isMouseDown = true;
this.drag = true;
}
});
this.equipContainer.addEventListener("mouseup", (e2) => {
this.isMouseDown = false;
clearInterval(this.mouseIntval);
});
this.dollContainer.addEventListener("mouseup", (e2) => {
this.isMouseDown = false;
clearInterval(this.mouseIntval);
});
this.dollContainer.addEventListener("click", (e2) => {
if (!this.autoUpdate)
this.eggDamage();
});
this.equipContainer.addEventListener("click", (e2) => {
if (!this.autoUpdate)
this.eggDamage();
});
};
PaperDoll.prototype.pointEggEvent = function(e2) {
if (this.autoUpdate && !this.isMouseDown || !this.autoUpdate && this.isMouseDown)
this.pointEgg(e2);
};
PaperDoll.prototype.pointEgg = function(e2) {
var rect = e2.target.getBoundingClientRect();
this.rotY = -((e2.x - rect.left) / rect.width) * 4 + 2;
this.rotX = ((e2.y - rect.top) / rect.height - 0.5) * 1.5;
};
PaperDoll.prototype.startRendering = function() {
var outer = this;
G.engine.runRenderLoop(function() {
outer.scene.render();
});
};
PaperDoll.prototype.avatars = function(callback) {
callback(this.avatar);
callback(this.dualAvatar);
};
PaperDoll.prototype.update = function(delta) {
this.camera.target.x += (this.camX - this.camera.target.x) / 5;
this.camera.target.y += (this.camY - this.camera.target.y) / 5;
this.camera.radius += (this.camRadius - this.camera.radius) / 5;
this.jump -= delta * 2e-3;
this.avatars((avatar) => {
avatar.actor.head.rotation.x += (this.rotX - avatar.actor.head.rotation.x) / 5;
avatar.actor.mesh_.rotation.y += (this.rotY - avatar.actor.mesh_.rotation.y) / 5;
avatar.actor.mesh_.rotation.x = avatar.actor.head.rotation.x * 0.5;
avatar.actor.mesh_.position.x = -avatar.actor.mesh_.rotation.y * 0.1;
avatar.actor.mesh_.position.y = Math.max(0, avatar.actor.mesh_.position.y + this.jump * delta);
});
if (!this.manualOrientation && this.autoUpdate) {
this.turnCountdown -= delta;
if (this.turnCountdown <= 0) {
var rx = Math.random() * 0.6 - 0.4;
var ry = Math.random() * 2 - 1 + this.camX * 0.5;
var d = Math.length2(rx - this.rotX, ry - this.rotY);
this.rotX = rx;
this.rotY = ry;
this.jump = Math.min(0.01, d / 100);
this.turnCountdown = Math.random() * 90 + 30;
}
}
this.fakeShadow.position.x = this.avatar.actor.mesh_.position.x;
this.fakeShadow.position.z = this.avatar.actor.mesh_.position.z;
};
PaperDoll.prototype.setupScene = function() {
this.scene = new BABYLON.Scene(G.engine);
loadMaterials(this.scene);
this.scene.autoClear = true;
this.scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
this.scene.fogMode = BABYLON.Scene.FOGMODE_EXP2;
this.scene.fogDensity = 0.06;
var skyColor = new BABYLON.Color3(0.35, 0.65, 0.8);
this.scene.fogColor = skyColor;
this.scene.sunLight = {
direction: new BABYLON.Vector3(0.2, 1, 0.1),
diffuse: new BABYLON.Color3.White()
};
this.camera = new BABYLON.ArcRotateCamera("", Math.PI * 0.5, 1.5, this.camRadius, new BABYLON.Vector3(this.camX, this.camY, 0), this.scene);
this.scene.activeCameras.push(this.camera);
this.camera.maxZ = 10;
this.camera.fov = 0.5;
this.camera.minZ = 0.1;
var shadowMat = new BABYLON.StandardMaterial("shadowMat", this.scene);
shadowMat.emissiveColor = new BABYLON.Color3(0.07, 0.57, 0.74);
shadowMat.alpha = 0.5;
this.fakeShadow = BABYLON.MeshBuilder.CreateDisc("fakeShadow", { radius: 0.25 }, this.scene);
this.fakeShadow.material = shadowMat;
this.fakeShadow.rotation.x = Math.PI / 2;
this.fakeShadow.position.y = 0;
this.scene.render();
stampTexture = new BABYLON.Texture("img/stamps.png?v=" + version, this.scene);
};
PaperDoll.prototype.poseWithItems = function(items) {
this.poseWithHat(items[ItemType2.Hat]);
this.poseWithStamp(items[ItemType2.Stamp]);
this.poseWithPrimaryWeapon(items[ItemType2.Primary]);
this.poseWithSecondaryWeapon(items[ItemType2.Secondary]);
this.poseWithGrenade(items[ItemType2.Grenade]);
this.poseWithMelee(items[ItemType2.Melee]);
};
PaperDoll.prototype.poseWithPrimaryWeapon = function(weaponItem) {
if (weaponItem === void 0)
return;
if (weaponItem !== null && this.posingItems[ItemType2.Primary] === weaponItem)
return;
this.avatar.weapon.actor.dispose();
if (weaponItem !== null) {
let weapon = weaponItem.instantiateNew(this.avatar);
this.avatar.weapon = weapon;
let actor = this.avatar.actor;
actor.setWeaponSkeleton(weapon.actor.skeleton);
actor.gripBone.setScale(new BABYLON.Vector3(1, -1, 1));
actor.gripBone.position = actor.weaponGripBone.position;
actor.gripBone.setRotationQuaternion(actor.weaponGripBone.rotationQuaternion);
this.dualAvatar.actor.foreBone.setScale(BABYLON.Vector3.Zero());
weapon.actor.gunMesh_.setEnabled(true);
}
this.posingItems[ItemType2.Primary] = weaponItem;
if (this.posingItems[ItemType2.Melee] !== null) {
this.poseWithMelee(this.posingItems[ItemType2.Melee], true);
}
};
PaperDoll.prototype.poseWithSecondaryWeapon = function(weaponItem) {
if (weaponItem === void 0)
return;
if (weaponItem !== null && this.posingItems[ItemType2.Secondary] === weaponItem)
return;
this.dualAvatar.weapon.actor.dispose();
if (weaponItem !== null) {
let weapon = weaponItem.instantiateNew(this.dualAvatar);
this.dualAvatar.weapon = weapon;
let actor = this.dualAvatar.actor;
actor.setWeaponSkeleton(weapon.actor.skeleton);
actor.gripBone.position = actor.weaponGripBone.position;
actor.gripBone.setRotationQuaternion(actor.weaponGripBone.rotationQuaternion);
weapon.actor.gunMesh_.setEnabled(true);
actor.gripBone.setScale(new BABYLON.Vector3(1, -1, 1));
this.avatar.actor.foreBone.setScale(BABYLON.Vector3.Zero());
if (this.posingItems[ItemType2.Grenade] !== null && !this.grenadeOnHip) {
let gMesh = this.dualAvatar.grenade.actor.mesh_;
gMesh.parent = this.dualAvatar.actor.mesh_;
gMesh.position.set(0.29, 0.17, -0.08);
gMesh.rotation.y = Math.PI + 0.3;
gMesh.rotation.z = -0.3;
this.grenadeOnHip = true;
}
}
this.posingItems[ItemType2.Secondary] = weaponItem;
if (this.posingItems[ItemType2.Grenade] !== null) {
this.poseWithGrenade(this.posingItems[ItemType2.Grenade], true);
}
};
PaperDoll.prototype.poseWithGrenade = function(grenadeItem, force) {
if (grenadeItem === void 0)
return;
if (!force && grenadeItem !== null && this.posingItems[ItemType2.Grenade] === grenadeItem)
return;
if (this.dualAvatar.grenade)
this.dualAvatar.grenade.actor.dispose();
if (grenadeItem !== null) {
this.dualAvatar.grenade = grenadeItem.instantiateNew(this.dualAvatar);
let mesh2 = this.dualAvatar.grenade.actor.mesh_;
mesh2.setEnabled(true);
if (this.posingItems[ItemType2.Secondary] !== null) {
mesh2.parent = this.dualAvatar.actor.mesh_;
mesh2.position.set(0.29, 0.17, -0.08);
mesh2.rotation.y = Math.PI + 0.3;
mesh2.rotation.z = -0.3;
this.grenadeOnHip = true;
} else {
mesh2.position.set(-0.25, 0, 0.3);
mesh2.rotation.y = Math.PI;
let actor = this.avatar.actor;
this.dualAvatar.actor.gripBone.setScale(BABYLON.Vector3.Zero());
actor.foreBone.setScale(new BABYLON.Vector3(-1, 1, 1));
this.grenadeOnHip = false;
actor.foreBone.position = new BABYLON.Vector3(-0.25, -0.11, 0.28);
actor.foreBone.setRotation(new BABYLON.Vector3(-1.7, 3, 0));
mesh2.parent = actor.head;
}
}
this.posingItems[ItemType2.Grenade] = grenadeItem;
};
PaperDoll.prototype.poseWithMelee = function(meleeItem, force) {
if (meleeItem === void 0)
return;
if (!force && meleeItem !== null && this.posingItems[ItemType2.Melee] === meleeItem)
return;
if (this.avatar.meleeWeapon)
this.avatar.meleeWeapon.actor.dispose();
if (meleeItem !== null) {
let weapon = meleeItem.instantiateNew(this.avatar);
this.avatar.meleeWeapon = weapon;
let mesh2 = weapon.actor.weaponMesh;
mesh2.setEnabled(true);
if (this.posingItems[ItemType2.Primary] !== null) {
mesh2.parent = this.avatar.actor.mesh_;
mesh2.position.set(-0.53, -0.02, 0.07);
mesh2.rotation.x = -2.1;
mesh2.rotation.y = -0.3;
} else {
mesh2.parent = this.avatar.actor.gunContainer;
this.avatar.actor.gripBone.setScale(new BABYLON.Vector3(1, -1, 1));
this.avatar.actor.gripBone.position = this.avatar.actor.weaponGripBone.position;
this.avatar.actor.gripBone.setRotationQuaternion(this.avatar.actor.weaponGripBone.rotationQuaternion);
this.dualAvatar.actor.foreBone.setScale(BABYLON.Vector3.Zero());
this.avatar.actor.wieldMelee();
}
}
this.posingItems[ItemType2.Melee] = meleeItem;
};
PaperDoll.prototype.poseWithHat = function(hatItem) {
if (hatItem === void 0)
return;
if (hatItem !== null && this.posingItems[ItemType2.Hat] === hatItem)
return;
this.avatar.actor.removeHat();
if (hatItem !== null) {
this.avatar.actor.wearHat(hatItem);
}
this.posingItems[ItemType2.Hat] = hatItem;
};
PaperDoll.prototype.poseWithStamp = function(stampItem) {
if (stampItem === void 0)
return;
if (stampItem !== null && this.posingItems[ItemType2.Stamp] === stampItem)
return;
this.avatar.actor.removeStamp();
if (stampItem !== null) {
this.avatar.actor.applyStamp(stampItem);
}
this.posingItems[ItemType2.Stamp] = stampItem;
};
PaperDoll.prototype.poseWithColor = function(colorIdx) {
if (colorIdx >= 7 && !G.playerAccount.isSubscriber) {
colorIdx = 0;
vueApp.equip.colorIdx = 0;
}
this.avatar.actor.setShellColor(colorIdx);
this.dualAvatar.actor.setShellColor(colorIdx);
vueApp.setShellColor(colorIdx);
};
PaperDoll.prototype.photoBoothHideItem = function(val) {
switch (val.value) {
case ItemType2.Hat:
if (hasValue(this.posingItems[val.value])) {
this.poseWithHat(null);
} else {
this.poseWithHat(G.playerAccount.hatItem);
}
break;
case ItemType2.Stamp:
if (this.posingItems[val.value]) {
this.poseWithStamp(null);
} else {
this.poseWithStamp(G.playerAccount.stampItem);
}
break;
case ItemType2.Grenade:
if (this.posingItems[val.value]) {
this.poseWithGrenade(null);
} else {
this.poseWithGrenade(G.playerAccount.grenadeItem);
}
break;
case ItemType2.Melee:
if (this.posingItems[val.value]) {
this.poseWithMelee(null);
} else {
this.poseWithMelee(G.playerAccount.meleeItem);
}
break;
case ItemType2.Primary:
if (this.posingItems[val.value]) {
this.poseWithPrimaryWeapon(null);
} else {
this.poseWithPrimaryWeapon(G.playerAccount.getPrimaryWeapon());
}
break;
case ItemType2.Secondary:
if (this.posingItems[val.value]) {
this.poseWithSecondaryWeapon(null);
} else {
this.poseWithSecondaryWeapon(G.playerAccount.getSecondaryWeapon());
}
break;
default:
break;
}
if (this.posingItems[ItemType2.Grenade] === null && this.posingItems[ItemType2.Secondary] === null) {
this.dualAvatar.actor.gripBone.setScale(BABYLON.Vector3.Zero());
this.avatar.actor.foreBone.setScale(new BABYLON.Vector3(1, -1, 1));
this.avatar.actor.foreBone.position = new BABYLON.Vector3(-0.34, -0.12, 0.1);
this.avatar.actor.foreBone.setRotation(new BABYLON.Vector3(0.3, 1.5, -1.2));
}
if (this.posingItems[ItemType2.Primary] === null && this.posingItems[ItemType2.Melee] === null) {
this.avatar.actor.gripBone.setScale(BABYLON.Vector3.Zero());
this.dualAvatar.actor.foreBone.setScale(new BABYLON.Vector3(1, -1, 1));
this.dualAvatar.actor.foreBone.position = new BABYLON.Vector3(-0.34, -0.12, 0.1);
this.dualAvatar.actor.foreBone.setRotation(new BABYLON.Vector3(0.3, 1.5, -1.2));
} else {
this.avatar.actor.gripBone.setScale(new BABYLON.Vector3(1, -1, 1));
this.dualAvatar.actor.foreBone.setScale(BABYLON.Vector3.Zero());
}
};
PaperDoll.prototype.scale = function(idx) {
if (idx === void 0)
idx = 0;
this.avatar.actor.mesh_.scaling = new BABYLON.Vector3(this.scaleSizes[idx], this.scaleSizes[idx], this.scaleSizes[idx]);
this.dualAvatar.actor.mesh_.scaling = new BABYLON.Vector3(this.scaleSizes[idx], this.scaleSizes[idx], this.scaleSizes[idx]);
this.fakeShadow.scaling = new BABYLON.Vector3(this.scaleSizes[idx], this.scaleSizes[idx], this.scaleSizes[idx]);
};
PaperDoll.prototype.eggDamage = function(reset) {
if (reset) {
this.avatar.hp_ = 100;
} else {
if (PhotoBooth.open && this.drag) {
this.avatar.hp_ = this.dmg > 0 ? this.dmg -= 25 : this.dmg += 100;
}
}
};
PaperDoll.prototype.photoBoothOpen = function() {
this.poseWithItems(G.playerAccount.getEquippedItems());
this.autoUpdate = false;
this.fakeShadow.material.emissiveColor = new BABYLON.Color3(0, 0, 0);
};
PaperDoll.prototype.photoBoothClose = function() {
this.autoUpdate = true;
this.fakeShadow.material.emissiveColor = new BABYLON.Color3(0.07, 0.57, 0.74);
this.eggDamage(true);
resetPaperDoll();
};
var PhotoBoothInstance = class {
constructor() {
this.isOpen = false;
this.zoomMsgRead = false;
}
hideItem(val) {
if (inGame && !this.isOpen) {
val = null;
}
paperDoll.photoBoothHideItem(val);
}
eggDollSize(val) {
if (inGame && !this.isOpen) {
val = 0;
}
paperDoll.scale(val);
}
zoooMsg() {
if (!this.zoomMsgRead) {
localStore.setItem("photoBoothZooming", true);
this.zoomMsgRead = localStore.getItem("photoBoothZooming");
vueApp.showGenericPopup("screen_photo_booth_zoom_title", "screen_photo_booth_zoom_msg", "ok");
}
}
getScreenshot(crop) {
this.zoooMsg();
if (!this.isOpen && inGame)
return;
if (crop) {
this.getScreenshotWithCrop();
return;
}
html2canvas(document.body, { allowTaint: false, logging: false, backgroundColor: null }).then((canvas2) => vueApp.screenGrabDone(canvas2.toDataURL()));
}
getScreenshotWithCrop() {
this.zoooMsg();
if (!this.isOpen && inGame)
return;
const cropper = document.createElement("canvas").getContext("2d");
const settings2 = { allowTaint: false, logging: false, backgroundColor: null };
const finalWidth = window.innerWidth;
const canvasWidth = finalWidth / 2;
const finalHeight = window.innerHeight;
settings2.height = finalHeight;
settings2.width = finalWidth;
settings2.x = Math.round(settings2.x);
return html2canvas(document.body, settings2).then((c) => {
cropper.canvas.width = canvasWidth;
cropper.canvas.height = finalHeight;
cropper.drawImage(c, -Math.max(0, (finalWidth - canvasWidth) / 2 || 0), -(+settings2.y || 0));
vueApp.screenGrabDone(cropper.canvas.toDataURL());
});
}
open() {
if (inGame) {
this.close();
return;
}
this.isOpen = true;
this.zoomMsgRead = localStorage.getItem("photoBoothZooming");
vueApp.$refs.photoBooth.open();
paperDoll.photoBoothOpen();
}
close() {
this.isOpen = false;
this.eggDollSize(0);
vueApp.$refs.photoBooth.close();
paperDoll.photoBoothClose();
}
};
function pingRegions(callback) {
console.log("Pinging regions");
var lowestPing = 1e6;
let wsProto = "https:" == document.location.protocol ? "wss" : "ws";
for (let r of Matchmaker.regionList) {
(function(region) {
let addr = `${isHttps() ? "wss" : "ws"}://` + getGameHostname(region.sub) + "/game/";
var pinger = new WebSocket(addr);
var startTime;
pinger.onopen = (e2) => {
console.log("Pinging " + region.id);
pinger.send(JSON.stringify({ command: "ping" }));
startTime = Date.now();
};
pinger.onmessage = (e2) => {
clearTimeout(timeout2);
r.ping = Date.now() - startTime;
vueApp.regionList = Matchmaker.regionList.filter((r2) => r2.ping !== null).sort((a, b2) => {
if (a.ping < b2.ping)
return -1;
if (a.ping > b2.ping)
return 1;
return 0;
});
if (r.ping < lowestPing) {
lowestPing = r.ping;
vueApp.currentRegionId = r.id;
}
};
pinger.onerror = (e2) => {
clearTimeout(timeout2);
r.ping = null;
};
var timeout2 = setTimeout(() => {
r.ping = null;
pinger.close();
}, 4e3);
})(r);
}
}
function selectRegion(regionId) {
let currentRegion = Matchmaker.regionList.find(function(r) {
return r.id === regionId;
});
if (!hasValue(currentRegion)) {
currentRegion = Matchmaker.regionList[0];
}
vueApp.currentRegionId = currentRegion.id;
localStore.setItem("selectedRegionId", currentRegion.id);
}
var shake;
function PlayerActor(player) {
this.player_ = player;
this.scene = this.player_.scene;
this.mesh_ = new BABYLON.TransformNode();
this.hat = null;
this.bodyMesh_ = cloneMesh("egg", this.scene, this.mesh_);
this.bodyMesh_._scene = this.scene;
this.bodyMesh_.position.y = 0.32;
this.bodyMesh_.player_ = this.player_;
this.lerpToPosition = new BABYLON.Vector3();
this.positionLerp = 0;
this.lerpFromPosition = new BABYLON.Vector3();
this.lerpTargetPosition = new BABYLON.Vector3();
this.bodyMesh_.material = getMaterialByName("eggShell", this.scene);
this.bodyMesh_.material.setTexture("textureSampler", stampTexture);
this.head = new BABYLON.TransformNode();
this.head.parent = this.mesh_;
this.head.position.y = 0.3;
this.head.position.z = 0;
this.gunContainer = new BABYLON.TransformNode();
this.gunContainer.parent = this.head;
this.gunContainer.rotation.y = -0.14;
this.gunContainer.rotation.x = -0.035;
this.setupStowAnims();
this.eye = new BABYLON.TransformNode();
this.eye.position.y = 0.1;
this.eye.position.x = 0;
this.eye.parent = this.head;
this.hands = cloneMesh("hands", this.scene, this.gunContainer);
this.hands.skeleton = cloneSkeleton("hands_skeleton", this.scene);
this.hands.material = getMaterialByName("standard", this.scene);
this.gripBone = this.hands.skeleton.bones[this.hands.skeleton.getBoneIndexByName("gripHand")];
this.foreBone = this.hands.skeleton.bones[this.hands.skeleton.getBoneIndexByName("foreHand")];
if (this.player_.shield > 0) {
this.bodyMesh_.overlayColor = Player.OverlayColor.green;
this.hands.overlayColor = Player.OverlayColor.green;
this.bodyMesh_.renderOverlay = true;
this.hands.renderOverlay = true;
}
this.setShellColor(this.player_.shellColor);
shake = 0;
this.mesh_.position.x = this.player_.x_;
this.mesh_.position.y = this.player_.y_;
this.mesh_.position.z = this.player_.z_;
if (this.player_.id != meId) {
this.wearHat(this.player_.hatItem);
this.applyStamp(this.player_.stampItem);
}
if (playOffline) {
this.hands.setEnabled(false);
}
this.bobbleIntensity = 0;
this.zoomed = false;
this.hitSoundDelay = 0;
this.auraSprite = null;
this.auraSpriteFrame = 0;
for (var i2 = 0; i2 < Object.keys(ShellStreak).length; i2++) {
var bit = Math.pow(2, i2);
if (this.player_.activeShellStreaks & bit) {
this.beginShellStreak(bit);
}
}
if (inGame) {
if (shadowGen)
shadowGen.getShadowMap().renderList.push(this.bodyMesh_);
if (this.player_.id == meId) {
this.hands.setRenderingGroupId(2);
} else {
this.setupNameSprite();
this.showSprites();
}
if (inGame)
this.updateTeam();
} else {
this.bodyMesh_.outlineColor = teamColors.outline[0];
}
}
PlayerActor.prototype.wearHat = function(hatItem) {
this.removeHat();
if (hatItem !== null) {
this.hat = cloneMesh(hatItem.item_data.meshName, this.scene, this.bodyMesh_);
this.hat.position.y = -0.02;
}
};
PlayerActor.prototype.removeHat = function() {
if (this.hat !== void 0 && this.hat !== null) {
this.hat.dispose();
}
};
PlayerActor.prototype.applyStamp = function(stampItem) {
this.removeStamp();
if (stampItem !== null) {
this.bodyMesh_.stampU = stampItem.item_data.x / 32;
this.bodyMesh_.stampV = 1 - stampItem.item_data.y / 32;
}
};
PlayerActor.prototype.removeStamp = function() {
this.bodyMesh_.stampU = 0;
this.bodyMesh_.stampV = 1;
};
PlayerActor.prototype.drawTextOnNameTexture = function(text, x, y, size, color, center) {
var shadowCoords = [{ x: 0, y: -4 }, { x: -4, y: 0 }, { x: 4, y: 0 }, { x: 0, y: 4 }];
var coords = [{ x: 0, y: -1 }, { x: -1, y: 0 }, { x: 1, y: 0 }, { x: 0, y: 1 }];
var tx = this.player_.id % 4 * 512;
var ty = 2048 - Math.floor(this.player_.id / 4) * 256;
x += tx;
y = -y + ty;
if (center) {
x += 256 - getFloatingNameWidth(text, size) / 2;
}
for (var i2 = 0; i2 < 4; i2++) {
nameTexture.drawText(text, x + shadowCoords[i2].x, y + shadowCoords[i2].y, "bold " + size + "px Nunito, sans-serif", "rgba(0, 0, 0, 0.5)", "transparent");
}
for (var i2 = 0; i2 < 4; i2++) {
nameTexture.drawText(text, x + coords[i2].x, y + coords[i2].y, "bold " + size + "px Nunito, sans-serif", color, "transparent");
}
};
PlayerActor.prototype.setupNameSprite = function() {
var tx = this.player_.id % 4 * 512;
var ty = 2048 - Math.floor(this.player_.id / 4) * 256;
nameTexture.clearRect(tx, ty - 256, 512, 256);
this.drawTextOnNameTexture(this.player_.name, 0, 32, 60, "white", true);
};
PlayerActor.prototype.updateTeam = function() {
if (this.player_.team == myTeam || spectate) {
this.bodyMesh_.outlineColor = teamColors.outline[this.player_.team];
} else {
this.bodyMesh_.outlineColor = teamColors.outline[0];
}
if (this.nameSprite) {
this.nameSprite.width = 0.6;
this.nameSprite.height = 0.3;
this.nameSprite.color = teamColors.textColor[this.player_.team];
}
};
PlayerActor.prototype.update = function(delta) {
var bcos = Math.cos(this.player_.bobble) * this.bobbleIntensity;
var bsina = Math.abs(Math.sin(this.player_.bobble) * this.bobbleIntensity);
var bsin = Math.sin(this.player_.bobble * 2) * this.bobbleIntensity;
if (this.player_.shield > 0) {
var alpha = Math.random() * 0.7 + 0.2;
this.bodyMesh_.overlayAlpha = alpha;
this.hands.overlayAlpha = alpha;
}
if (this.player_.activeShellStreaks & ShellStreak.EggBreaker) {
var alpha = Math.cos(now / 100) * 0.5 + 0.5;
this.bodyMesh_.overlayAlpha = alpha;
this.hands.overlayAlpha = alpha;
}
delta = Math.min(delta, 1);
var mult = 0.333 * delta;
if (this.player_.id == meId) {
if (this.player_.scope && this.player_.isAtReady(true)) {
camera.fov = camera.fov + (this.player_.weapon.actor.scopeFov - camera.fov) * mult;
this.gunContainer.rotation.y *= mult;
this.gunContainer.rotation.x *= mult;
this.gunContainer.position.x += (-0.24999999 - this.gunContainer.position.x) * mult;
this.gunContainer.position.y += (this.player_.weapon.actor.scopeY - this.gunContainer.position.y) * mult;
this.gunContainer.position.z += (-0.05 - this.gunContainer.position.z) * mult;
if (this.player_.weapon.hasScope && !this.zoomed && camera.fov < this.player_.weapon.actor.scopeFov + 0.05) {
scope.show();
this.gunContainer.setEnabled(false);
this.zoomed = true;
}
} else {
camera.fov = camera.fov + (1.25 - camera.fov) * mult;
var iMult = 1 - mult;
this.gunContainer.rotation.y += (-0.14 + bcos * 2 - this.gunContainer.rotation.y) * mult;
this.gunContainer.rotation.x += (-0.035 + bsin * 0.75 - this.gunContainer.rotation.x) * mult;
this.gunContainer.position.x *= iMult;
this.gunContainer.position.y *= iMult;
this.gunContainer.position.z *= iMult;
if (this.zoomed && camera.fov > this.player_.weapon.actor.scopeFov + 0.05) {
scope.hide();
this.gunContainer.setEnabled(true);
this.zoomed = false;
}
}
} else {
this.gunContainer.rotation.y += (-0.14 + bcos * 2 - this.gunContainer.rotation.y) * mult;
this.gunContainer.rotation.x += (-0.035 + bsin * 0.75 - this.gunContainer.rotation.x) * mult;
if (this.player_.team > 0 && (this.player_.team == myTeam || spectate) && this.nameSprite) {
var dist = Math.length3(this.player_.x_ - me.x_, this.player_.y_ - me.y_, this.player_.z_ - me.z_);
var fac = Math.pow(dist, 1.25);
this.nameSprite.width = fac / 10 + 0.6;
this.nameSprite.height = fac / 20 + 0.3;
}
}
this.lerpToPosition.copyFromFloats(this.player_.x_, this.player_.y_, this.player_.z_);
BABYLON.Vector3.LerpToRef(this.lerpFromPosition, this.lerpToPosition, Math.min(this.positionLerp, 1), this.lerpTargetPosition);
this.positionLerp += delta / 2;
this.mesh_.position.x += (this.lerpTargetPosition.x - this.mesh_.position.x) * 0.5;
this.mesh_.position.y += (this.lerpTargetPosition.y - this.mesh_.position.y) * 0.5;
this.mesh_.position.z += (this.lerpTargetPosition.z - this.mesh_.position.z) * 0.5;
if (this.player_.id !== meId) {
var diffYaw = Math.radDifference(this.player_.yaw_, this.mesh_.rotation.y);
var diffPitch = Math.radDifference(this.player_.pitch_, this.head.rotation.x);
this.mesh_.rotation.y += diffYaw / 2 * delta;
this.head.rotation.x += diffPitch / 2 * delta;
} else {
this.mesh_.rotation.y = this.player_.yaw_;
this.head.rotation.x = this.player_.pitch_;
}
this.bodyMesh_.rotation.x = this.head.rotation.x / 4;
var bobbleTarget;
if (!this.player_.onGround && !this.player_.climbing) {
bobbleTarget = 0;
} else {
bobbleTarget = Math.length3(this.player_.dx, this.player_.dy, this.player_.dz);
}
this.bobbleIntensity += (bobbleTarget - this.bobbleIntensity) / 10;
this.bodyMesh_.rotation.z = bcos * 5;
this.bodyMesh_.position.y = bsina * 1.5 + 0.32;
if (shake > 0) {
shake *= 0.9;
if (shake < 1e-3) {
shake = 0;
} else {
var x = Math.random() * shake - shake * 0.5;
var y = Math.random() * shake - shake * 0.5;
var z = Math.random() * shake - shake * 0.5;
this.eye.rotation.x += (x - this.eye.rotation.x) / 10;
this.eye.rotation.y += (y - this.eye.rotation.y) / 10;
this.eye.rotation.z += (z - this.eye.rotation.z) / 10;
}
} else {
this.eye.rotation.x *= 0.9;
this.eye.rotation.y *= 0.9;
this.eye.rotation.z *= 0.9;
}
if (this.player_.id != viewingPlayerId) {
var visible = isMeshVisible(this.mesh_, 0.31);
this.mesh_.setVisible(visible);
if (visible) {
this.showSprites();
} else {
this.hideSprites();
}
if (this.nameSprite) {
this.positionSprites();
}
}
this.hitSoundDelay = Math.max(this.hitSoundDelay - delta, 0);
if (this.player_.weapon.actor)
this.player_.weapon.actor.update(delta);
};
PlayerActor.prototype.updateLerp = function() {
this.positionLerp = 0;
this.lerpFromPosition.copyFromFloats(this.player_.x_, this.player_.y_, this.player_.z_);
};
PlayerActor.prototype.resetLerp = function() {
this.mesh_.position.x = this.player_.x_;
this.mesh_.position.y = this.player_.y_;
this.mesh_.position.z = this.player_.z_;
this.positionLerp = 0;
this.lerpToPosition.copyFromFloats(this.player_.x_, this.player_.y_, this.player_.z_);
this.lerpFromPosition.copyFromFloats(this.player_.x_, this.player_.y_, this.player_.z_);
this.lerpTargetPosition.copyFromFloats(this.player_.x_, this.player_.y_, this.player_.z_);
};
PlayerActor.v3_1 = new BABYLON.Vector3();
PlayerActor.v3_2 = new BABYLON.Vector3();
PlayerActor.prototype.positionSprites = function() {
if (this.nameSprite) {
var mp = PlayerActor.v3_1;
mp.copyFrom(this.mesh_.position);
mp.y += this.nameSprite.height * 0.5 + 0.65;
var v = this.nameSprite.position;
v.copyFrom(camera.globalPosition);
v.subtractInPlace(mp);
v.normalize();
v.scaleInPlace(0.4);
v.addInPlace(mp);
}
if (this.auraSprite) {
var mp = PlayerActor.v3_1;
mp.copyFrom(this.mesh_.position);
mp.y += 0.35;
var v = this.auraSprite.position;
v.copyFrom(camera.globalPosition);
v.subtractInPlace(mp);
v.normalize();
v.scaleInPlace(0.4);
v.addInPlace(mp);
}
};
PlayerActor.prototype.showSprites = function() {
if (this.player_.playing) {
if (!this.nameSprite) {
this.nameSprite = new BABYLON.Sprite("", nameSprites);
this.nameSprite.invertV = true;
this.nameSprite.width = 0.6;
this.nameSprite.height = 0.3;
this.nameSprite.cellIndex = this.player_.id;
this.nameSprite.color = teamColors.textColor[this.player_.team];
if (this.player_.team == myTeam || spectate) {
this.bodyMesh_.outlineColor = teamColors.outline[this.player_.team];
} else {
this.bodyMesh_.outlineColor = teamColors.outline[0];
}
}
if (!this.auraSprite && this.player_.activeShellStreaks & ShellStreak.HardBoiled) {
this.auraSprite = new BABYLON.Sprite("", auraSprites);
this.auraSprite.invertV = true;
this.auraSprite.width = 0.7;
this.auraSprite.height = 0.7;
this.auraSprite.playAnimation(this.auraSpriteFrame, this.auraSpriteFrame + 7, true, 67);
}
}
};
PlayerActor.prototype.hideSprites = function() {
if (this.nameSprite) {
this.nameSprite.dispose();
this.nameSprite = null;
}
if (this.auraSprite) {
this.auraSprite.dispose();
this.auraSprite = null;
}
};
PlayerActor.prototype.hit = function() {
if (this.hitSoundDelay <= 0) {
if (this.player_.activeShellStreaks & ShellStreak.HardBoiled) {
pAudio.play("shield_hit", this.bodyMesh_.absolutePosition, true);
} else {
pAudio.play("hit", this.bodyMesh_.absolutePosition, true);
}
this.hitSoundDelay = 10;
}
};
PlayerActor.prototype.beginShellStreak = function(ksType) {
switch (ksType) {
case ShellStreak.HardBoiled:
this.auraSpriteFrame = 8;
if (this.player_.id == meId) {
showShellStreakMessage("HARD BOILED");
updateHealthUI();
}
break;
case ShellStreak.EggBreaker:
if (this.player_.id == meId) {
showShellStreakMessage("EGG BREAKER");
reticle.setPowerful(true);
document.getElementById("eggBreakerContainer").className = "on";
}
this.bodyMesh_.overlayColor = Player.OverlayColor.red;
this.hands.overlayColor = Player.OverlayColor.red;
this.bodyMesh_.renderOverlay = true;
this.hands.renderOverlay = true;
break;
}
this.showSprites();
};
PlayerActor.prototype.endShellStreak = function(ksType) {
switch (ksType) {
case ShellStreak.HardBoiled:
if (this.player_.id == meId) {
updateHealthUI();
}
if (this.auraSprite) {
this.auraSprite.dispose();
this.auraSprite = null;
}
break;
case ShellStreak.EggBreaker:
if (this.player_.id == meId) {
reticle.setPowerful(false);
document.getElementById("eggBreakerContainer").className = "off";
}
this.bodyMesh_.renderOverlay = false;
this.hands.renderOverlay = false;
}
};
PlayerActor.prototype.removeFromPlay = function() {
this.zoomed = false;
this.throwingGrenade = false;
this.gripBone._frozen = false;
this.wieldingMelee = false;
this.mesh_.setEnabled(false);
this.hideSprites();
};
PlayerActor.prototype.restoreToPlay = function() {
this.mesh_.setEnabled(true);
this.gunContainer.setEnabled(true);
if (this.player_.id != meId)
this.showSprites();
};
PlayerActor.prototype.remove = function() {
this.mesh_.dispose();
this.hideSprites();
};
PlayerActor.prototype.fire = function() {
if (this.zoomed && this.player_.weapon.hasScope) {
shake = 0.15;
this.eye.rotation.x = -0.05;
} else if (settings.shakeEnabled) {
shake = 0.08 * camera.fov;
}
if (this.wieldingMelee) {
this.wieldGun();
}
};
PlayerActor.prototype.inspect = function() {
if (this.player_.weapon && !this.player_.scope && this.player_.canSwapOrReload()) {
this.player_.weapon.actor.inspect();
}
};
PlayerActor.prototype.melee = function() {
if (this.player_.id === meId)
shake = 0.05;
if (!this.wieldingMelee) {
this.wieldMelee();
}
this.player_.meleeWeapon.actor.attack();
};
PlayerActor.prototype.wieldMelee = function() {
this.wieldingMelee = true;
this.player_.weapon.actor.restPose();
this.setWeaponSkeleton(this.player_.meleeWeapon.actor.skeleton);
this.player_.meleeWeapon.actor.weaponMesh.setEnabled(true);
this.player_.weapon.actor.gunMesh_.setEnabled(false);
};
PlayerActor.prototype.wieldGun = function() {
this.wieldingMelee = false;
this.setWeaponSkeleton(this.player_.weapon.actor.skeleton);
this.player_.meleeWeapon.actor.weaponMesh.setEnabled(false);
this.player_.weapon.actor.gunMesh_.setEnabled(true);
};
PlayerActor.prototype.reachForGrenade = function() {
this.player_.weapon.actor.restPose();
this.throwingGrenade = true;
this.gripBone._frozen = true;
this.hands.skeleton.enableBlending(0.2);
this.hands.skeleton.beginAnimation("grenade_grab", false, 1, () => {
if (this.hands.skeleton)
this.hands.skeleton.disableBlending();
});
};
PlayerActor.prototype.throwGrenade = function() {
var that = this;
if (this.player_.id == meId) {
document.getElementById("grenadeThrowContainer").style.visibility = "hidden";
}
this.hands.skeleton.beginAnimation("grenade_throw", false, 1, function() {
if (that.hands.skeleton) {
that.throwingGrenade = false;
that.gripBone._frozen = false;
}
});
};
PlayerActor.prototype.setShellColor = function(colorIdx) {
if (colorIdx < 0 || colorIdx >= shellColors.length) {
console.log("Shell color out of bounds: " + colorIdx);
colorIdx = 0;
}
var color = BABYLON.Color3.FromHexString(shellColors[colorIdx]);
this.bodyMesh_.colorMult = color;
this.hands.colorMult = color;
};
PlayerActor.prototype.setWeaponSkeleton = function(skeleton) {
this.skeleton = skeleton;
this.weaponGripBone = this.skeleton.bones[this.skeleton.getBoneIndexByName("gripHand")];
this.weaponForeBone = this.skeleton.bones[this.skeleton.getBoneIndexByName("foreHand")];
};
PlayerActor.prototype.handsToWeaponSkeleton = function() {
this.gripBone.position = this.weaponGripBone.position;
this.gripBone.setRotationQuaternion(this.weaponGripBone.rotationQuaternion);
if (this.throwingGrenade == true)
return;
this.foreBone.position = this.weaponForeBone.position;
this.foreBone.setRotationQuaternion(this.weaponForeBone.rotationQuaternion);
};
PlayerActor.prototype.setupStowAnims = function(restRotation, flipped) {
restRotation = restRotation === void 0 ? -0.14 : restRotation;
flipped = flipped ? -1 : 1;
var gunRotationAnimation = new BABYLON.Animation("", "rotation", 60, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
var gunScaleAnimation = new BABYLON.Animation("", "scaling", 60, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
var gunPositionAnimation = new BABYLON.Animation("", "position", 60, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
var gunRotationEase = new BABYLON.CubicEase();
gunRotationEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
gunRotationAnimation.setEasingFunction(gunRotationEase);
var gunScaleEase = new BABYLON.CubicEase();
gunScaleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
gunScaleAnimation.setEasingFunction(gunScaleEase);
var gunPositionEase = new BABYLON.CubicEase();
gunPositionEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
gunPositionAnimation.setEasingFunction(gunPositionEase);
var gunRotationKeys = [
{ frame: 0, value: new BABYLON.Vector3(-0.035, restRotation * flipped, 0) },
{ frame: 25, value: new BABYLON.Vector3(1, -1.5 * flipped, 0) },
{ frame: 30, value: new BABYLON.Vector3(-1, -1.5 * flipped, 0) },
{ frame: 55, value: new BABYLON.Vector3(-0.035, restRotation * flipped, 0) }
];
var gunScaleKeys = [
{ frame: 0, value: new BABYLON.Vector3(1, 1, 1) },
{ frame: 25, value: new BABYLON.Vector3(0.25 * flipped, 0.25, 0.25) },
{ frame: 30, value: new BABYLON.Vector3(0.25 * flipped, 0.25, 0.25) },
{ frame: 55, value: new BABYLON.Vector3(1 * flipped, 1, 1) }
];
var gunPositionKeys = [
{ frame: 0, value: new BABYLON.Vector3(0, 0, 0) },
{ frame: 25, value: new BABYLON.Vector3(0.1 * flipped, 0.1, -0.2) },
{ frame: 30, value: new BABYLON.Vector3(0.1 * flipped, 0, -0.2) },
{ frame: 55, value: new BABYLON.Vector3(0, 0, 0) }
];
gunRotationAnimation.setKeys(gunRotationKeys);
gunScaleAnimation.setKeys(gunScaleKeys);
gunPositionAnimation.setKeys(gunPositionKeys);
this.gunContainer.animations.push(gunRotationAnimation);
this.gunContainer.animations.push(gunScaleAnimation);
this.gunContainer.animations.push(gunPositionAnimation);
};
Player.OverlayColor = {
green: BABYLON.Color3.Green(),
red: new BABYLON.Color3(255, 0, 0)
};
var pokiInitTracking = () => {
if (!pokiActive)
return;
if (thirdPartyAdblocker)
return;
if (typeof googletag !== "undefined" && window.googletag && googletag.apiReady) {
googletag.pubads().addEventListener("impressionViewable", (event) => {
const slotId = event.slot.getSlotElementId(), parent = document.getElementById(slotId).parentNode, parentId = parent.id;
if (parentId)
ga("send", "event", "Poki", "Display ad", parentId);
});
}
};
var pokiRewardedBreak = (callback, errorCallback2) => {
if (!pokiActive)
return;
setVolume(0);
PokiSDK.rewardedBreak().then(
() => {
pokiCurrencyReward();
if (callback) {
callback(Reward.video);
}
setVolume();
console.log("POKI Reward given");
}
).catch(
(err) => {
console.log("Reward failed. ", err);
if (errorCallback2) {
errorCallback2();
}
setVolume();
}
);
};
var pokiGameLoadingStart = () => {
if (!pokiActive)
return;
PokiSDK.gameLoadingStart();
};
var pokiGameLoadingFinished = () => {
if (!pokiActive)
return;
PokiSDK.gameLoadingFinished();
};
var pokiGamePlayStart = () => {
if (!pokiActive)
return;
PokiSDK.gameplayStart();
};
var pokiGamePlayStop = () => {
if (!pokiActive)
return;
PokiSDK.gameplayStop();
};
var pokiHappyTime = (intensity) => {
if (!pokiActive)
return;
PokiSDK.happyTime(intensity);
};
var pokiCurrencyReward = () => {
};
var isItTimeForPokiReward = () => {
if (!pokiActive)
return;
vueData.isPokiGameLoad = true;
};
var clearPokiRewardTimer = () => {
if (!pokiActive)
return;
console.log("clearPokiRewardTimer");
vueData.isPokiGameLoad = false;
vueData.isPokiNewRewardTimer = false;
vueData.pokiRewardReady = false;
};
var Product = class {
constructor() {
this.currencies = [];
this.items = [];
this.subscriptions = [];
this.initalized = false;
}
init() {
if (SsProducts === null || SsProducts === void 0) {
console.log("No products");
return;
}
this.currencies = SsProducts.filter((pro) => pro.type === "currency");
this.items = SsProducts.filter((pro) => pro.type === "item");
this.subscriptions = SsProducts.filter((pro) => pro.type === "subscription");
this.bundles = SsProducts.filter((pro) => pro.type === "bundle");
this.initalized = true;
}
getBySku(sku) {
if (!this.initalized) {
return;
}
return SsProducts.filter((pro) => pro.sku === sku);
}
getShopItems() {
if (!this.initalized) {
return;
}
return SsProducts.filter((pro) => pro.isActive && pro.type === "item");
}
getStoreItems() {
if (!this.initalized) {
return;
}
return SsProducts.filter((pro) => pro.inStore && pro.isActive);
}
getSubscriptions() {
if (!this.initalized) {
return;
}
return SsProducts.filter((sub) => sub.type === "subscription" && sub.isActive);
}
getBundles() {
if (!this.initalized) {
return;
}
return SsProducts.filter((sub) => sub.type === "bundle" && sub.isActive);
}
getBundlesByItemId(itemId) {
return this.getBundles().filter((a) => {
if (a.length != itemId.length) {
return [];
} else {
let result = [];
for (let i2 = 0; i2 < a.length; i2++) {
if (a[i2] !== b[i2]) {
return [];
} else {
result = a;
}
}
return a;
}
});
}
getProductType(sku) {
const product = SsProducts.filter((pro) => pro.sku === sku);
if (product.hasOwnProperty("length") && product.length > 0 && product[0].hasOwnProperty("type")) {
return product[0].type;
}
}
getActiveByType(type) {
if (!this.initalized) {
return;
}
return this[type].filter((pro) => pro.isActive);
}
getProductTitleByEggVaule(value) {
if (!this.initalized) {
return;
}
let prod = this.currencies.filter((pro) => pro.currency == value);
if (prod.length > 0) {
return prod[0].sku;
}
}
};
var ReliableWebSocket = class {
constructor(url) {
this.url = url;
this.ws = null;
this.queue = [];
this.reconnectTimeout = null;
this.reconnectTimeoutTime = 0;
this.pingInterval = null;
this.connect(url);
}
connect() {
if (this.ws && (this.ws.readyState === WebSocket.CONNECTING || this.ws.readyState === WebSocket.OPEN)) {
return;
}
console.log(`ReliableWebSocket: Connecting to ${this.url}`);
try {
this.ws = new WebSocket(this.url);
} catch (e2) {
this._onerror(e2);
return;
}
this.ws.onopen = () => {
console.log(`ReliableWebSocket: Connected to ${this.url}`);
this.reconnectTimeoutTime = 0;
this.queue.forEach((message) => {
this.ws.send(message);
});
this.queue = [];
this.pingInterval = setInterval(() => {
this.ws.send("ping");
}, 3e4);
this.onopen();
};
this.ws.onclose = (e2) => {
console.log(`ReliableWebSocket: Disconnected from ${this.url} with code ${e2.code} - Attempting to reconnect in ${this.reconnectTimeoutTime} seconds...`);
clearInterval(this.pingInterval);
if (e2.code !== CloseCode.NORMAL_CLOSURE && !this.reconnectTimeout) {
this.reconnectTimeout = setTimeout(() => {
this.reconnectTimeout = null;
this.connect();
}, this.reconnectTimeoutTime * 1e3);
this.reconnectTimeoutTime = Math.min(this.reconnectTimeoutTime + 1, 10);
}
this.onclose(e2);
};
this.ws.onerror = (e2) => this._onerror(e2);
this.ws.onmessage = (e2) => this.onmessage(e2);
}
send(message) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(message);
} else {
this.queue.push(message);
if (this.ws.readyState !== WebSocket.CONNECTING) {
this.connect();
}
}
}
_onerror(e2) {
if (this.reconnectTimeoutTime > 4) {
this.queue = [];
this.onerror(e2);
}
}
onopen() {
}
onclose(e2) {
}
onmessage(e2) {
}
onerror(e2) {
}
};
function RocketActor(rocket) {
this.rocket = rocket;
this.scene = rocket.scene;
this.armed = false;
this.delayFrames = 0;
this.mesh_ = this.scene.getMeshByName("rocket").createInstance("");
this.mesh_.setEnabled(false);
}
RocketActor.v3_1 = new BABYLON.Vector3();
RocketActor.prototype.fire = function() {
this.armed = false;
this.delayFrames = 2;
this.mesh_.position.x = this.rocket.x;
this.mesh_.position.y = this.rocket.y;
this.mesh_.position.z = this.rocket.z;
var v = RocketActor.v3_1;
v.set(
this.rocket.x + this.rocket.dx,
this.rocket.y + this.rocket.dy,
this.rocket.z + this.rocket.dz
);
this.mesh_.lookAt(v);
};
RocketActor.prototype.update = function() {
if (--this.delayFrames <= 0) {
this.mesh_.setEnabled(true);
}
if (!this.armed && this.rocket.minRange <= 0) {
this.armed = true;
pAudio.play("gun_rpegg_rocket_fly", this.mesh_.position, true);
}
if (this.delayFrames % 2 == 0) {
var size = 0.4;
var dx = Math.random() * 0.04 - 0.02;
var dy = Math.random() * 0.04 - 0.02;
var dz = Math.random() * 0.04 - 0.02;
if (this.armed) {
addExplosionSprite(explosionSmokeManager, 30, this.rocket.x, this.rocket.y, this.rocket.z, dx, dy, dz, size, false, null);
addExplosionSprite(explosionFireManager, 10, this.rocket.x, this.rocket.y, this.rocket.z, dx, dy, dz, size, false, null);
}
}
this.mesh_.position.x += (this.rocket.x - this.mesh_.position.x) * 0.5;
this.mesh_.position.y += (this.rocket.y - this.mesh_.position.y) * 0.5;
this.mesh_.position.z += (this.rocket.z - this.mesh_.position.z) * 0.5;
};
RocketActor.prototype.remove = function() {
this.mesh_.setEnabled(false);
};
var debug = false;
var isLocalShellDev = location.hostname.startsWith("localshelldev");
var isLocalHost = location.hostname.startsWith("localhost");
G.servicesServer = `${isHttps() ? "wss" : "ws"}://${location.hostname}/services/`;
var portalTest = new URLSearchParams(location.search).get("portalTest");
if (portalTest) {
dynamicContentRoot = `${portalTest}.shellshock.io`;
dynamicContentPrefix = `https://${portalTest}.shellshock.io/`;
}
if (dynamicContentRoot) {
G.servicesServer = `${isHttps() ? "wss" : "ws"}://` + dynamicContentRoot + "/services/";
} else if (isLocalHost || isLocalShellDev || location.hostname.startsWith("staging")) {
debug = true;
}
function loadSettings() {
settings = {
volume: getStoredNumber("volume", 1),
mouseSensitivity: getStoredNumber("mouseSensitivity", null),
mouseSpeed: getStoredNumber("mouseSpeed", 50),
mouseInvert: getStoredNumber("mouseInvert", 1),
fastPollMouse: getStoredBool("fastPollMouse", false),
holdToAim: getStoredBool("holdToAim", true),
enableChat: getStoredBool("enableChat", true),
safeNames: getStoredBool("safeNames", false),
autoDetail: getStoredBool("autoDetail", true),
shadowsEnabled: getStoredBool("shadowsEnabled", true),
highRes: getStoredBool("highRes", true),
controllerSpeed: getStoredNumber("controllerSpeed", 20),
deadzone: getStoredNumber("deadzone", 0.3),
controllerInvert: getStoredNumber("controllerInvert", 1),
controls: getStoredObject("controls", getDefaultControls()),
musicVolume: getStoredNumber("musicVolume", 0.5),
musicStatus: getStoredBool("musicStatus", true),
hideBadge: getStoredBool("hideBadge", false),
closeWindowAlert: getStoredBool("closeWindowAlert", false),
shakeEnabled: getStoredBool("shakeEnabled", true),
centerDot: getStoredBool("centerDot", true),
hitMarkers: getStoredBool("hitMarkers", true)
};
if (!settings.mouseSpeed && settings.mouseSensitivity !== null) {
settings.mouseSpeed = Math.floor(Math.sqrt(settings.mouseSensitivity * 350) + 19);
localStore.removeItem("mouseSensitivity");
}
fillMissingControls();
setInputMap(settings.controls);
vueApp.setUiSettings(settings);
}
function saveSettings() {
localStore.setItem("volume", settings.volume);
localStore.setItem("mouseSpeed", settings.mouseSpeed);
localStore.setItem("mouseInvert", settings.mouseInvert);
localStore.setItem("fastPollMouse", settings.fastPollMouse);
localStore.setItem("holdToAim", settings.holdToAim);
localStore.setItem("enableChat", settings.enableChat);
localStore.setItem("safeNames", settings.safeNames);
localStore.setItem("autoDetail", settings.autoDetail);
localStore.setItem("shadowsEnabled", settings.shadowsEnabled);
localStore.setItem("highRes", settings.highRes);
localStore.setItem("controllerSpeed", settings.controllerSpeed);
localStore.setItem("deadzone", settings.deadzone);
localStore.setItem("controllerInvert", settings.controllerInvert);
localStore.setItem("controls", JSON.stringify(settings.controls));
localStore.setItem("musicVolume", settings.musicVolume);
localStore.setItem("musicStatus", settings.musicStatus);
localStore.setItem("hideBadge", settings.hideBadge);
localStore.setItem("closeWindowAlert", settings.closeWindowAlert);
localStore.setItem("shakeEnabled", settings.shakeEnabled);
localStore.setItem("centerDot", settings.centerDot);
localStore.setItem("hitMarkers", settings.hitMarkers);
}
function applyUiSettings(settingsUi, originalSettings) {
Object.values(settingsUi.adjusters).forEach((v) => {
v.forEach((s) => {
settings[s.id] = s.value;
});
});
Object.values(settingsUi.togglers).forEach((v) => {
v.forEach((s) => {
if (s.id === "mouseInvert" || s.id == "controllerInvert") {
settings[s.id] = s.value ? -1 : 1;
} else {
settings[s.id] = s.value;
}
});
});
settingsUi.controls.keyboard.game.forEach((s) => {
settings.controls.keyboard.game[s.id] = s.value;
});
settingsUi.controls.keyboard.spectate.forEach((s) => {
settings.controls.keyboard.spectate[s.id] = s.value;
});
settingsUi.controls.gamepad.game.forEach((s) => {
settings.controls.gamepad.game[s.id] = s.value;
});
settingsUi.controls.gamepad.spectate.forEach((s) => {
settings.controls.gamepad.spectate[s.id] = s.value;
});
setInputMap(settings.controls);
setVolume();
setMouseSpeed(settings.mouseSpeed);
setControllerSpeed(settings.controllerSpeed);
setDeadzone(settings.deadzone);
enableChat(settings.enableChat);
if (gameScene) {
if (!settings.autoDetail) {
setHighRes(settings.highRes);
setShadows(settings.shadowsEnabled);
disableAutoDetail();
} else if (!originalSettings.autoDetail) {
setHighRes(true);
setShadows(true);
enableAutoDetail();
}
if (settings.centerDot) {
reticle.showDot();
} else {
reticle.hideDot();
}
if (settings.hitMarkers) {
hitMarkers.show();
} else {
hitMarkers.hide();
}
}
saveSettings();
}
function setInputMap(controls) {
inputToControlMap = {
keyboard: { game: {}, spectate: {} },
gamepad: { game: {}, spectate: {} }
};
Object.keys(controls.keyboard).forEach((cat) => {
Object.keys(controls.keyboard[cat]).forEach((k) => {
inputToControlMap.keyboard[cat][controls.keyboard[cat][k]] = k;
});
});
Object.keys(controls.gamepad).forEach((cat) => {
Object.keys(controls.gamepad[cat]).forEach((k) => {
inputToControlMap.gamepad[cat][controls.gamepad[cat][k]] = k;
});
});
}
function getDefaultControls() {
return {
keyboard: {
game: {
up: "W",
down: "S",
left: "A",
right: "D",
jump: "SPACE",
melee: "F",
inspect: "G",
fire: "MOUSE 0",
scope: "SHIFT",
reload: "R",
swap_weapon: "E",
grenade: "Q"
},
spectate: {
ascend: "SPACE",
descend: "SHIFT",
toggle_freecam: "V"
}
},
gamepad: {
game: {
jump: 0,
fire: 7,
scope: 6,
reload: 2,
swap_weapon: 3,
grenade: 5,
melee: 1,
inspect: 4
},
spectate: {
ascend: 6,
descend: 7
}
}
};
}
function fillMissingControls() {
function recurse(defaults, current) {
Object.keys(defaults).forEach((k) => {
if (typeof defaults[k] === "object") {
if (!current[k])
current[k] = {};
recurse(defaults[k], current[k]);
} else {
if (!current[k])
current[k] = defaults[k];
}
});
}
recurse(getDefaultControls(), settings.controls);
}
function resetSettings() {
localStore.removeItem("volume");
localStore.removeItem("mouseSensitivity");
localStore.removeItem("mouseSpeed");
localStore.removeItem("mouseInvert");
localStore.removeItem("fastPollMouse");
localStore.removeItem("holdToAim");
localStore.removeItem("enableChat");
localStore.removeItem("safeNames");
localStore.removeItem("autoDetail");
localStore.removeItem("shadowsEnabled");
localStore.removeItem("highRes");
localStore.removeItem("controlConfig");
localStore.removeItem("controllerSpeed");
localStore.removeItem("deadzone");
localStore.removeItem("controllerInvert");
localStore.removeItem("controls");
localStore.removeItem("hideBadge");
localStore.removeItem("closeWindowAlert");
localStore.removeItem("shakeEnabled");
localStore.removeItem("centerDot");
loadSettings();
}
function setVolume(volume, musicVol) {
if (volume === 0) {
console.log("game volume suspended");
vueApp.volume = 0;
BAWK.setVolume(0);
return BAWK.suspend();
}
volume = volume || settings.volume;
console.log("volume set to: " + volume);
BAWK.resume();
BAWK.setVolume(volume);
vueApp.volume = volume;
}
function setMouseSpeed(value) {
settings.mouseSpeed = value;
}
function setControllerSpeed(value) {
settings.controllerSpeed = value;
}
function setDeadzone(value) {
settings.deadzone = value;
}
BABYLON.Effect.ShadersStore["standardVertexShader"] = "\n#include\n#include\n\nprecision lowp float;\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\nattribute vec4 color;\nattribute vec2 uv;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 viewProjection;\nuniform mat4 shadowLightMat;\nuniform vec3 cameraPosition;\nuniform vec3 colorMult;\n\n// Varying\nvarying vec4 vPositionFromLight;\nvarying vec3 vPositionFromCamera;\nvarying vec3 vNormal;\nvarying vec4 vColor;\nvarying vec4 vEmissiveColor;\nvarying float fFogDistance;\n\n#ifdef EGGSHELL\n varying vec2 vUV;\n#endif\n\n/*\nvec4 distort(vec4 p)\n{\n vec2 v = p.xy / p.w;\n\n // Convert to polar coords:\n float theta = atan(v.y,v.x);\n float radius = length(v);\n\n // Distort:\n radius = pow(radius, 0.9);\n\n // Convert back to Cartesian:\n v.x = radius * cos(theta);\n v.y = radius * sin(theta);\n p.xy = v.xy * p.w;\n return p;\n}\n*/\n\n// MAIN\nvoid main(void) {\n #include\n #include\n vec4 worldPosition = finalWorld * vec4(position, 1.);\n\n #ifdef RECEIVESHADOWS\n vPositionFromLight = shadowLightMat * worldPosition;\n #endif\n\n vNormal = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n vColor = color;\n \n #ifdef COLORMULT\n vColor.rgb *= colorMult;\n #endif\n\n #ifdef COLORIZE\n vColor.rgb = colorMult;\n #endif\n\n fFogDistance = (view * worldPosition).z;\n gl_Position = viewProjection * worldPosition;\n\n #ifdef EGGSHELL\n vUV = uv;\n vPositionFromCamera = normalize(cameraPosition - worldPosition.xyz);\n #endif\n}\n";
BABYLON.Effect.ShadersStore["standardPixelShader"] = "\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nprecision lowp float;\n\n// Uniforms\nuniform sampler2D shadowSampler;\nuniform vec3 shadowParams;\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nuniform vec3 emissiveColor;\nuniform mat4 worldView;\nuniform float hp;\nuniform vec3 colorMult;\nuniform vec4 outlineColor;\nuniform sampler2D textureSampler;\nuniform vec2 stampOffset;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\n\n// Varying\nvarying vec4 vPositionFromLight;\nvarying vec3 vPositionFromCamera;\nvarying vec4 vColor;\nvarying vec2 vUV;\nvarying vec3 vNormal;\nvarying float fFogDistance;\n\nconst float sOff = .001;\n\n// FUNCTIONS\nfloat unpack(vec4 color)\n{\n const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\n}\n\nfloat random(vec2 p)\n{\n vec2 K1 = vec2(23.14069263277926, 2.665144142690225);\n return fract(cos(dot(p, K1)) * 12345.6789);\n}\n\nfloat calcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity); // Exp2\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n #ifndef SHADOWFULLFLOAT\n float shadow = unpack(texture2D(shadowSampler, uv));\n #else\n float shadow = texture2D(shadowSampler, uv).x;\n #endif\n\n if (depth.z < shadow) return 1.;\n float s = clamp((depth.z - shadow) * 12. + 0.5, 0.5, 1.0);\n return min(1.0, max(s, length(vPositionFromLight.xy)));\n}\n\nvec3 desaturate(vec3 color, float amount)\n{\n vec3 gray = vec3(dot(vec3(0.2126,0.7152,0.0722), color));\n return vec3(mix(color, gray, amount));\n}\n\n// MAIN\nvoid main(void)\n{\n vec4 color = vColor;\n\n #ifdef EGGSHELL // Show cracks and stamp texture!\n color.rgb = min((color.rgb - 0.5) * 4. + hp + 2., 1.);\n color.rgb *= colorMult;\n vec2 uv = clamp(vUV, vec2(0., 0.96875), vec2(.03125, 1.));\n //vec2 uv = clamp(vUV, vec2(0., 0.9375), vec2(.0625, 1.));\n uv += stampOffset;\n color.rgb = mix(color.rgb, texture2D(textureSampler, uv).rgb, texture2D(textureSampler, uv).a);\n #endif\n\n #ifdef RECEIVESHADOWS\n float s = computeShadow(vPositionFromLight, shadowSampler, shadowParams.x);\n color *= vec4(s, s, s, 1.);\n #endif\n\n #ifndef MAP // Not the map; use dynamic light\n color.rgb *= max(max(0.3, -vNormal.y * 0.4), dot(vNormal, sunDirection * 1.) + 0.4);\n color.rgb *= sunColor;\n #endif\n\n #ifdef FLASH\n color.rgb += emissiveColor;\n #endif\n\n float fog = calcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n\n #ifdef EGGSHELL\n float f = step(dot(vNormal, vPositionFromCamera), 0.4);\n color.rgb = mix(color.rgb, outlineColor.rgb, f * outlineColor.a);\n #endif\n\n gl_FragColor = color;\n}\n";
function SpatulaActor(spatula2, scene) {
this.spatula = spatula2;
this.scene = spatula2.scene;
this.mesh_ = this.scene.cloneMesh("spatula");
this.mesh_.emissiveColor = new BABYLON.Color3(0.8, 0.6, 0.2);
this.mesh_.setRenderingGroupId(1);
}
SpatulaActor.prototype.dispose = function() {
this.mesh_.dispose();
};
SpatulaActor.prototype.drop = function() {
this.mesh_.parent = null;
BAWK.play("drop_spatula");
};
SpatulaActor.prototype.update = function(delta) {
this.mesh_.position.x += (this.spatula.x - this.mesh_.position.x) * 0.5;
this.mesh_.position.y += (this.spatula.y + 0.1 - this.mesh_.position.y) * 0.5;
this.mesh_.position.z += (this.spatula.z - this.mesh_.position.z) * 0.5;
if (this.spatula.controlledBy == 255) {
this.mesh_.rotation.y += 0.1 * delta;
} else {
var player = players[this.spatula.controlledBy];
if (player) {
this.mesh_.rotation.y = player.yaw_;
}
}
};
function Spectator() {
this.dx = 0;
this.dy = 0;
this.dz = 0;
this.playerIdx = 0;
}
var Spectate = {
freeCamera: 0,
firstPerson: 1
};
Player.v1 = new BABYLON.Vector3();
Player.v2 = new BABYLON.Vector3();
Player.ray = new BABYLON.Ray();
Player.matrix = new BABYLON.Matrix();
Spectator.prototype.firstPerson = function() {
let player = players[this.playerIdx];
if (!(player && player.playing && this.playerIdx !== meId)) {
player = this.findNextPlayer();
}
if (!player)
return;
this.spectatePlayer(player);
};
Spectator.prototype.freeCamera = function() {
if (viewingPlayerId !== meId) {
me.pitch_ = camera.rotation.x;
me.yaw_ = camera.rotation.y;
}
camera.parent = null;
camera.lockedTarget = null;
viewingPlayerId = meId;
viewingPlayer = me;
controlKeys = 0;
vueData.ui.game.spectatingPlayerName = null;
this.restorePreviousPlayerActor();
};
Spectator.prototype.restorePreviousPlayerActor = function() {
let player = players[this.playerIdx];
if (player) {
if (player.actor.hat)
player.actor.hat.setVisible(true);
}
};
Spectator.prototype.spectatePlayer = function(player) {
this.restorePreviousPlayerActor();
this.playerIdx = player.id;
viewingPlayerId = player.id;
viewingPlayer = player;
player.actor.mesh_.setVisible(true);
if (player.actor.hat)
player.actor.hat.setVisible(false);
camera.lockedTarget = null;
mapOverview = false;
rebuildPlayerList();
vueData.ui.game.spectatingPlayerName = player.name;
gameScene.autoClear = true;
gameScene.autoClearDepthAndStencil = true;
};
Spectator.prototype.spectateNextPlayer = function(dir = 1) {
let player = this.findNextPlayer(dir);
if (player) {
this.spectatePlayer(player);
}
};
Spectator.prototype.findNextPlayer = function(dir = 1) {
let startListIdx = null;
var playerIdxs = [];
for (var i2 = 0; i2 < playerLimit; i2++) {
let p = players[i2];
if (p)
playerIdxs.push(p.id);
}
if (playerIdxs.length === 0) {
this.unlock();
return null;
}
metaGameUI.sortPlayerList(playerIdxs);
for (let i3 = 0; i3 < playerIdxs.length; i3++) {
if (players[playerIdxs[i3]].id === this.playerIdx) {
startListIdx = i3;
break;
}
}
if (startListIdx === null)
startListIdx = 0;
let theListIdx = startListIdx;
for (; ; ) {
theListIdx = Math.mod(theListIdx + dir, playerIdxs.length);
if (theListIdx === startListIdx)
break;
let player = players[playerIdxs[theListIdx]];
if (player && player.playing && player.id !== meId) {
return player;
}
}
this.unlock();
return null;
};
Spectator.prototype.unlock = function() {
viewingPlayerId = null;
viewingPlayer = null;
this.playerIdx = null;
};
Spectator.prototype.update = function(delta) {
if (spectateMode === Spectate.firstPerson) {
if (viewingPlayer && viewingPlayer.playing) {
camera.position.copyFrom(viewingPlayer.actor.eye.getAbsolutePosition());
camera.rotation.y = viewingPlayer.actor.mesh_.rotation.y;
camera.rotation.x = viewingPlayer.actor.head.rotation.x;
}
} else {
var dx = 0;
var dy = 0;
var dz = 0;
if (controlKeys & CONTROL.left) {
dx -= Math.cos(me.yaw_);
dz += Math.sin(me.yaw_);
}
if (controlKeys & CONTROL.right) {
dx += Math.cos(me.yaw_);
dz -= Math.sin(me.yaw_);
}
if (controlKeys & CONTROL.up) {
dx += Math.sin(me.yaw_);
dz += Math.cos(me.yaw_);
}
if (controlKeys & CONTROL.down) {
dx -= Math.sin(me.yaw_);
dz -= Math.cos(me.yaw_);
}
if (controlKeys & CONTROL.ascend) {
dy = 1;
}
if (controlKeys & CONTROL.descend) {
dy = -1;
}
var deltaVector = new BABYLON.Vector3(dx, dy, dz).normalize();
var pdx2 = this.dx;
var pdy = this.dy;
var pdz2 = this.dz;
this.dx += deltaVector.x * 0.016;
this.dy += deltaVector.y * 8e-3;
this.dz += deltaVector.z * 0.016;
var ndx = 0.5 * (this.dx + pdx2);
var ndy = 0.5 * (this.dy + pdy);
var ndz = 0.5 * (this.dz + pdz2);
camera.position.x += ndx * delta;
camera.position.y += ndy * delta;
camera.position.z += ndz * delta;
camera.position.y = Math.max(1.5, camera.position.y);
me.x_ = camera.position.x;
me.y_ = camera.position.y;
me.z_ = camera.position.z;
this.dx *= Math.pow(0.85, delta);
this.dy *= Math.pow(0.85, delta);
this.dz *= Math.pow(0.85, delta);
camera.rotation.x = me.pitch_;
camera.rotation.y = me.yaw_;
}
};
function fetchTwitchStreams() {
getRequest("data/twitchStreams.json?" + Date.now(), (err, res) => {
if (!err) {
let streams = JSON.parse(res);
console.log(streams);
streams.sort((a, b2) => {
return b2.viewers - a.viewers;
});
let streamsArray = streams.map((stream) => {
return {
name: stream.name,
viewers: stream.viewers,
link: "https://twitch.tv/" + stream.name,
image: dynamicContentPrefix + "data/img/twitchAvatars/" + stream.avatar
};
});
vueApp.twitchStreams = streamsArray;
}
}, function(err) {
console.log("Failed to load Twitch streamers");
vueApp.twitchStreams = [];
});
}
window.addEventListener("contextmenu", function(e2) {
e2.preventDefault();
}, false);
window.onresize = function() {
resize();
};
window.mobileAndTabletcheck = function() {
var check = false;
(function(a) {
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4)))
check = true;
})(navigator.userAgent || navigator.vendor || window.opera);
if (/Googlebot/i.test(navigator.userAgent))
check = false;
return check;
};
window.onloadingcomplete = function() {
if (typeof startVue === "undefined" || typeof firebase === "undefined") {
setTimeout(window.onloadingcomplete, 100);
return;
}
if (playShellshockers()) {
console.log("startShellShockers");
startShellShockers("en.json");
window.onload = null;
return;
}
const currentURL = location.protocol + "//" + location.host;
window.location.href = currentURL + "/portals";
};
window.onbeforeunload = () => {
if (inGame && settings.closeWindowAlert) {
e.preventDefault();
e.returnValue = "Are you sure you want to exit?";
return e.returnValue;
}
if (inGame && hasValue(SessionStats.sessionStart)) {
gaSessionPlayTime(gameStartTime, maps[mapIdx].name);
gaSendPlayerStats(SessionStats.end());
gaSendGameStats();
}
};
function buyProductForMoney(sku) {
if (parsedUrl.dom + parsedUrl.top === "devshellshock" && !localStore.getItem("xsollaPopupConfrim")) {
vueApp.openDevXsollaPopup(sku);
return;
}
selectedSku = sku;
getXsollaToken(sku, shellProducts.getProductType(sku) === "subscription" ? true : false);
localStore.removeItem("xsollaPopupConfrim");
}
function buyGoldenChicken() {
getXsollaToken("golden_chicken_pass");
}
function getPlayerPortalSource() {
let playerSource = "Shell Shockers";
if (pokiActive) {
playerSource = "Poki";
} else if (crazyGamesActive) {
playerSource = "Crazy Games";
}
return playerSource;
}
function getXsollaToken(productSku, subscription) {
const playerSource = getPlayerPortalSource();
console.log("getXsollaToken called (firebase ID: {0})".format(G.playerAccount.firebaseId), subscription);
selectedSku = productSku;
if (G.playerAccount.isAnonymous || !G.playerAccount.isEmailVerified) {
vueApp.denyAnonUser();
return;
}
var onXsollaTokenResponse = function(xsollaTokenResponse) {
if (xsollaTokenResponse.error) {
console.log("xsollaTokenResponse Error: " + JSON.stringify(xsollaTokenResponse));
disableProductPurchasing();
} else {
console.log("response: " + JSON.stringify(xsollaTokenResponse));
if (xsollaTokenResponse.result == "SUCCESS") {
console.log("Got Xsolla token: " + xsollaTokenResponse.token);
openXsollaPayStation(xsollaTokenResponse.token);
console.log(xsollaTokenResponse);
} else {
console.log("Failed to get Xsolla token");
purchasingFailed();
}
}
};
var onXsollaTokenError = function(xsollaTokenError) {
console.log("Error getting Xsolla token: " + JSON.stringify(xsollaTokenError));
purchasingFailed();
};
api_xsollaToken(productSku, onXsollaTokenResponse, onXsollaTokenError, subscription, playerSource);
}
var xsollaAnalytics = () => {
if (!hasValue(selectedSku)) {
return;
}
let skuObj = vueData.eggStoreItems.filter((obj) => obj.sku === selectedSku), product = skuObj[0], sku = product.sku, salePrice = product.salePrice ? Math.round(product.salePrice) : "", regPrice = Math.round(product.price), price = salePrice ? salePrice : regPrice;
if (!hasValue(sku) && !hasValue(price)) {
console.log("No Price no sku");
selectedSku = null;
return;
}
let skuRef = vueApp.eggStoreReferral ? sku + " " + vueApp.eggStoreReferral : sku;
selectedSku = null;
return ga("send", "event", vueApp.googleAnalytics.cat.purchases, vueApp.googleAnalytics.action.purchaseComplete, skuRef, price);
};
function openXsollaPayStation(xsollaToken) {
var options = {
access_token: xsollaToken,
sandbox: location.hostname.startsWith("localshelldev") || location.hostname.startsWith("staging"),
lightbox: {
spinner: "round",
overlayOpacity: 0.8
}
};
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
s.src = "//static.xsolla.com/embed/paystation/1.0.7/widget.min.js";
s.addEventListener("load", function(e2) {
XPayStationWidget.on("init", function(e3) {
console.log("Xsolla PayStation initialized");
XPayStationWidget.open();
});
XPayStationWidget.on("close", function(e3) {
console.log("Xsolla PayStation closed");
if (inGame) {
vueApp.showGameMenu();
vueApp.setDarkOverlay(false);
} else {
vueApp.toggleTitleScreenAd(true);
}
setTimeout(function() {
api_checkBalance();
checkUpgrade();
}, 3e3);
});
XPayStationWidget.on("open", function(e3) {
if (inGame) {
vueApp.hideGameMenu();
} else {
vueApp.toggleTitleScreenAd(false);
}
console.log("Xsolla PayStation open");
console.log(selectedSku);
});
XPayStationWidget.on("status", function(e3) {
console.log("Xsolla PayStation status");
console.log("status", e3);
console.log(selectedSku);
});
XPayStationWidget.on("status-invoice", function(e3) {
console.log("Xsolla PayStation status-invoice");
console.log("status-invoice", e3);
console.log(selectedSku);
});
XPayStationWidget.on("status-delivering", function(e3) {
console.log("Xsolla PayStation status-delivering");
console.log("status-delivering", e3);
console.log(selectedSku);
});
XPayStationWidget.on("status-done", function(e3) {
console.log("Xsolla PayStation status-done");
console.log("status-done", e3);
console.log(selectedSku);
localStore.setItem("xsollaPurchase", true);
if (selectedSku === "golden_chicken_pass") {
pokiHappyTime(1);
}
xsollaAnalytics();
});
XPayStationWidget.init(options);
}, false);
var head = document.getElementsByTagName("head")[0];
head.appendChild(s);
xsollaSetup = true;
}
function purchasingFailed() {
vueApp.showGenericPopup("uh_oh", "purchase_disabled", "ok");
}
MetaGameKing.state = {
start: 0,
score: 1,
win: 2,
capturing: 3,
contested: 4,
takeover: 5,
abandoned: 6,
unclaimed: 7
};
MetaGameKing.captureSpeeds = [1 * 1.2, 1.25 * 1.2, 1.7 * 1.2, 2.5 * 1.2, 4 * 1.2];
MetaGameKing.goalScore = 5;
MetaGameKing.takeOverTime = 90;
MetaGameKing.takeOverSpeed = 1;
var MapTools = class {
static normalizeManhattan(vec) {
var xx = Math.abs(vec.x);
var yy = Math.abs(vec.y);
var zz = Math.abs(vec.z);
var l = Math.max(xx, Math.max(yy, zz));
if (l == 0) {
vec.x = 0;
vec.y = 0;
vec.z = 0;
} else {
vec.x = Math.trunc(vec.x / l) * 0.5;
vec.y = Math.trunc(vec.y / l) * 0.5;
vec.z = Math.trunc(vec.z / l) * 0.5;
}
if (vec.x * vec.y != 0 || vec.x * vec.z != 0 || vec.y * vec.z != 0)
return true;
return false;
}
static stripTris(mapData, mapMeshes2, inMesh, particles) {
var inIndices = inMesh.getIndices();
var inPositions = inMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
var inNormals = inMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
var va = new BABYLON.Vector3();
var vb = new BABYLON.Vector3();
var outIndices = [];
var vec = { x: 0, y: 0, z: 0 };
for (var i2 = 0; i2 < inIndices.length; i2 += 3) {
var keep = false;
var px = 0, py = 0, pz = 0;
var nx = 0, ny = 0, nz = 0;
for (var t = 0; t < 3; t++) {
var idx = inIndices[i2 + t];
var part = particles[idx];
idx *= 3;
if (part) {
px = inPositions[idx + 0];
py = inPositions[idx + 1];
pz = inPositions[idx + 2];
vec.x = px - part.x;
vec.y = py - part.y;
vec.z = pz - part.z;
var onCorner = this.normalizeManhattan(vec);
var nx = inNormals[idx + 0] * 0.75;
var ny = inNormals[idx + 1] * 0.75;
var nz = inNormals[idx + 2] * 0.75;
if (onCorner) {
va.set(nx, ny, nz).normalize();
vb.set(vec.x, vec.y, vec.z).normalize();
var dot = BABYLON.Vector3.Dot(va, vb);
if (dot < 0.5) {
keep = true;
break;
}
var cx = Math.floor(part.x + nx + 0.5);
var cy = Math.floor(part.y + ny + 0.5);
var cz = Math.floor(part.z + nz + 0.5);
} else {
var cx = Math.floor(px + vec.x + 0.5);
var cy = Math.floor(py + vec.y + 0.5);
var cz = Math.floor(pz + vec.z + 0.5);
}
if (!keep) {
try {
var cel = mapData[cx][cy][cz];
if (cel && cel.idx) {
if (!mapMeshes2[cel.idx].name.endsWith(".full") || mapMeshes2[cel.idx].theme === "SPECIAL") {
keep = true;
break;
}
} else {
keep = true;
break;
}
} catch (e2) {
keep = true;
break;
}
}
} else {
keep = true;
break;
}
}
if (keep) {
outIndices.push(inIndices[i2 + 0]);
outIndices.push(inIndices[i2 + 1]);
outIndices.push(inIndices[i2 + 2]);
}
}
inMesh.setIndices(outIndices);
return inMesh;
}
static createMapCells(scene, meshIndex, minMap2, specificMeshName, zoneIdx, callback) {
var meshNames;
var keyIdx = 0;
if (specificMeshName) {
if (!minMap2.data[specificMeshName]) {
callback();
return;
}
meshNames = [specificMeshName];
} else {
meshNames = Object.keys(minMap2.data);
}
var particles = [];
var SPS = new BABYLON.SolidParticleSystem("SPS", scene, { updatable: true });
SPS.computeParticleColor = false;
SPS.computeParticleTexture = false;
SPS.computeParticleRotation = false;
SPS.recomputeNormals = false;
function addMeshToMap(keyIdx2) {
if (keyIdx2 == meshNames.length) {
var mesh2 = SPS.buildMesh();
callback(mesh2, particles);
return;
}
var meshName = meshNames[keyIdx2];
var meshData = minMap2.data[meshName];
var meshIdx = meshIndex[meshName];
var mesh2 = mapMeshes[meshIdx];
if (mesh2 === void 0) {
console.log("mesh not found: " + meshName);
}
var fields = meshName.split(".");
mesh2.theme = fields[0];
mesh2.colliderType = fields[2];
mesh2.softness = fields[3];
if (mesh2.theme != "SPECIAL" && (mesh2.theme != "DYNAMIC" || specificMeshName)) {
var i2 = 0;
var meshArr = Object.values(meshData).filter((m) => !zoneIdx || m.zone == zoneIdx);
var part;
SPS.addShape(mesh2, meshArr.length, {
positionFunction: function(particle, idx, shapeIdx) {
var rx = meshArr[i2].rx || 0;
var ry = meshArr[i2].ry || 0;
var rz = meshArr[i2].rz || 0;
particle.position.x = meshArr[i2].x + minMap2.extents.x.min;
particle.position.y = meshArr[i2].y + minMap2.extents.y.min;
particle.position.z = meshArr[i2].z + minMap2.extents.z.min;
particle.rotation.x = rx * rotInc;
particle.rotation.y = ry * rotInc;
particle.rotation.z = rz * rotInc;
particle.alive = false;
if (meshName.endsWith(".full") || meshName.includes("capture-zone")) {
part = {
x: particle.position.x,
y: particle.position.y,
z: particle.position.z
};
} else {
part = 0;
}
i2++;
},
vertexFunction: function(particle, vertex, i3) {
particles.push(part);
}
});
}
var nextFunction2 = addMeshToMap.bind(this, keyIdx2 + 1);
window.requestAnimationFrame(nextFunction2);
}
var nextFunction = addMeshToMap.bind(this, 0);
window.requestAnimationFrame(nextFunction);
}
};
window.extern = {
catalog: G.catalog,
play,
getLanguageData,
continueStartup,
showSignInDialog,
signOut,
sendFirebaseVerificationEmail,
selectRegion,
generateRandomName,
changeClass,
toggleFullscreen,
applyUiSettings,
resetSettings,
setVolume,
// setMusicVolume: setMusicVolume,
setSafeNames,
setMouseSpeed,
setControllerSpeed,
setDeadzone,
setShadows,
// setMusicStatus: setMusicStatus,
renderItemToCanvas,
getEquippedItems,
getTaggedItems,
getPremiumItems,
getItemsOfType,
isItemOwned,
tryEquipItem,
poseWithItems: (items) => paperDoll.poseWithItems(items),
setShellColor,
api_checkBalance,
checkUpgrade,
api_buy,
api_redeem,
saveEquipment,
buyGoldenChicken,
checkStartChicknWinner,
api_feedback,
releaseKeys,
captureKeys,
respawn,
leaveGame,
openEquipInGame,
closeEquipInGame,
buyProductForMoney,
clickedHouseAdSmall,
clickedHouseAdBig,
clickedHouseLink,
doConsent,
doNotConsent,
setOfAge,
setTargetedAds,
settingsMenuOpened,
copyFriendCode,
switchTeam,
onChatKeyDown,
startChat,
stopChat,
selectGameType,
inviteFriends,
hasHouseLink,
enterSpectatorMode,
fixStringWidth,
filterUnicode,
clickedWebFeedItem,
pokiRewardedBreak,
api_inGameReward,
socialReward,
getHouseAd,
getLocText,
GameType,
// chwRadialProgress: chwRadialProgress,
resize,
giveBasketBrosReward,
resetPaperDoll,
getSessionStats,
getProductTitle,
chwTryPlay,
api_incentivizedVideoRewardRequest,
getProductTitleByEggVaule,
accountCreationNotification,
sendChat,
getActiveBundles,
sendGameOptions,
sendGameOptionsMetrics,
sendGameAction,
GameOptions,
GameActions,
GameFlags,
get metaGame() {
return metaGame;
},
get metaGameUI() {
return metaGameUI;
},
get isPrivateGame() {
return isPrivateGame;
},
get observingGame() {
return observingGame;
},
get isGameOwner() {
return isGameOwner;
},
get adminRoles() {
return G.adminRoles;
},
get photoBooth() {
return PhotoBooth;
},
get isGameReady() {
return allSystemsGo();
},
get inGame() {
return inGame;
},
get gamePaused() {
return gamePaused;
},
get gameType() {
return gameType;
},
get specialItemsTag() {
return houseAds.specialItemsTag;
},
get getPwaEvent() {
return pwaDeferredPrompt;
},
// **UI** TEST
get account() {
return G.playerAccount;
},
// If ads are blocked.
get productBlockAds() {
return G.productBlockAds;
},
// if it is an ad blocker of some kind
get adBlocker() {
return adBlocker;
},
get version() {
return version;
},
get changelogData() {
return changelogData;
},
get onJoinGameClick() {
return joinGameAttempted;
},
get adsLoaded() {
return adsLoaded;
},
get openShopOnly() {
return openShopOnly;
},
set openShopOnly(val) {
openShopOnly = val;
},
set onJoinGameClick(val) {
joinGameAttempted = val;
},
get fuseOptions() {
return ItemSearchSettings;
},
get gameOptions() {
return gameOptions;
},
set gameOptions(val) {
gameOptions = val;
},
testGameUI
};
})();